How to get index from Arraylist which contains string - java

Below is my model:
public class Products {
String date = "", item = "";
public Products () {
}
public Products (String date String item ) {
this.date = date
this.item = item ;
}
public String getdate() {
return date
}
public void setdate (String date) {
this.date = date
}
public String getitem () {
return item
}
public void setitem (String item) {
this.item = item
}
}
And below code for defined the Arralist:
private ArrayList<TasksCharts> mArrayList;
and i have data in ArrayList:
position 0 -> date - "2016-10-02" , item = "pens"
position 1 -> date - "2016-10-03" , item = "xyz"
position 2 -> date - "2016-10-03" , item = "fts"
Now i want the position of ArraList whose contain "pens" . So for that i have eritten below code:
if (containsSubString(mArrayList, "pens")) {
int listIndex = getItemPos("pens");
}
private int getItemPos(String item) {
return mArrayList.indexOf(item);
}
When i runt this it will give me -1 index for item pens.
How can i get the index of particular item ?

Does a TasksCharts Object containing pens equal a String Object containing pens?
Unless you have overriden the equals method I would say "no".
I would recommend that you use a Map instead or you will have to loop through looking for a TasksCharts Object containing pens

You can run a for loop to get job done .
private int getItempos(ArrayList<TasksCharts> mArrayList, String str)
{
for(int i=0;i<mArrayList.size();i++)
{
if(mArrayList.get(i).item.indexOf(str)!=-1)
{
return i;
}
}
return -1;
}
Hope this helps!

you should do sth like this :
private int getItemPos(String key , String item) {
int i = 0;
for (i=0; i<mArrayList.size(); i++)
{
if(mArrayList.get(i).get(key).equalsIgnoreCase(item))
{
return i;
}
}
return -1;
}
and call
int x = getItemPos("item" , "pen");

I have simply added products in the same ArrayList and then used for-loop to find that product position.
ArrayList<Products> mArrayList = new ArrayList<>();
Products products1 = new Products("2016-10-05", "Pens");
Products products2 = new Products("2016-10-04", "Pencil");
Products products3 = new Products("2016-10-03", "Book");
Products products4 = new Products("2016-10-02", "Dairy");
mArrayList.add(products1);
mArrayList.add(products2);
mArrayList.add(products3);
mArrayList.add(products4);
for (Products products : mArrayList) {
if (products.getitem().equals("Pens")) {
Log.d("Position", mArrayList.indexOf(products) + "");
}
}
This will give Output as
D/Position: 0

Related

sort by date java basic list

I have a list in java that contains lines of string id;city;date;days;price;vehicle. I need to sort all of it by date.(it's from a csv file that I read)
My list:
List <Ticket> list = new LinkedList<Ticket>();
And the way it is defined:
class Ticket {
int id;
String city;
String date;
int days;
float price;
String vehicle;
Ticket(int i, String c, String y, int d, float p, String v) {
id = i;
city = c;
date = y;
days = d;
price = p;
vehicle = v;
}
I was trying bubble sort but I have no clue how to compare dates and all the examples I found had ArrayList or were comparing small amounts of dates. I'm sorry if this is a bad question I just don't know how to apply everything I found to my situation.
You can do this with Comparator interface. I prefer to convert the string into date first.
For dd/MM/yyyy (01/01/1970) pattern example (without conversion):
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list, new Comparator<Ticket>() {
public int compare(Ticket t1, Ticket t2) {
String[] dateParts1 = t1.date.split("/");
String[] dateParts2 = t2.date.split("/");
int yearResult = dateParts1[2].compareTo(dateParts2[2]);
if (yearResult != 0) {
return yearResult;
}
int monthResult = dateParts1[1].compareTo(dateParts2[1]);
if (monthResult != 0) {
return monthResult;
}
int dayResult = dateParts1[0].compareTo(dateParts2[0]);
if (dayResult != 0) {
return dayResult;
}
return 0;
}
});
or (with conversion):
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list2, new Comparator<Ticket>() {
public int compare(Ticket t1, Ticket t2) {
String pattern = "dd/MM/yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
try {
Date date1 = simpleDateFormat.parse(t1.date);
Date date2 = simpleDateFormat.parse(t2.date);
return date1.compareTo(date2);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
Also, you can do same thing in class with Comparable interface.
public class Ticket **implements Comparable<Ticket>** {
int id;
String city;
String date;
int days;
float price;
String vehicle;
Ticket(int i, String c, String y, int d, float p, String v) {
id = i;
city = c;
date = y;
days = d;
price = p;
vehicle = v;
}
**#Override
public int compareTo(Ticket o) {
String[] dateParts1 = this.date.split("/");
String[] dateParts2 = o.date.split("/");
int yearResult = dateParts1[2].compareTo(dateParts2[2]);
if (yearResult != 0) {
return yearResult;
}
int monthResult = dateParts1[1].compareTo(dateParts2[1]);
if (monthResult != 0) {
return monthResult;
}
int dayResult = dateParts1[0].compareTo(dateParts2[0]);
if (dayResult != 0) {
return dayResult;
}
return 0;
}**
}
Then:
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list);
You can parse the date String to a date object like LocalDateTime or Instant and etc' (depending on your use case).
I randomly picked LocalDateTime for this example.
Then you can do:
tickets.add(new Ticket(1, "dsa", LocalDateTime.now().plusSeconds(5), 6, 5, "rew"));
tickets.add(new Ticket(0, "dsa", LocalDateTime.now(), 6, 5, "rew"));
List<Ticket> sortedTicketsByDate = tickets.stream()
.sorted(Comparator.comparing(t -> t.date)) // comparing by date
.collect(Collectors.toList());
System.out.println(sortedTicketsByDate);
Output:
[
Ticket(id=0, city=dsa, date=2021-05-02T23:46:03.214, days=6, price=5.0, vehicle=rew),
Ticket(id=1, city=dsa, date=2021-05-02T23:46:08.197, days=6, price=5.0, vehicle=rew)
]
Here is another clean version using java records (new since JDK 16) which is recommended for plain java objects (pojos) that store data.
Read more info in this article : https://www.baeldung.com/java-record-keyword
You implement the Comparable interface based on date and Collections.Sort() can sort your ArrayList based on that.
import java.util.ArrayList;
import java.util.Collections;
record Ticket(int id,String city,String date,int days,float price,String vehicle) implements Comparable<Ticket>{
public int compareTo(Ticket ticket){
return this.date.compareTo(ticket.date);
}
}
public class Main{
public static void main(String[] args) {
Ticket ticket1 = new Ticket(1,"New York","2021-05-03",10,110.30f,"Ferrari");
Ticket ticket2 = new Ticket(2,"Miami","2021-05-02",9,120.50f,"Porche");
Ticket ticket3 = new Ticket(3,"Los Angeles","2021-05-01",10,150.50f,"Mercedes");
var list = new ArrayList<Ticket>();
list.add(ticket1);
list.add(ticket2);
list.add(ticket3);
System.out.println("The List before sorting:\n");
list.forEach(System.out::println);
Collections.sort(list);
System.out.println("\nThe List After sorting:\n");
list.forEach(System.out::println);
}
}

Loop and return each item individually

I am using MpAndroidChart library and trying to set custom labels using this method:
String[] daysOfTheWeek = {"M","T","W","T","F","S","S"};
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() { //Returns a string not a list :(
#Override
public String getFormattedValue(float value) {
int position = 0;
for(int i =0; i<daysOfTheWeek.length;i++){
position = i;
}
return daysOfTheWeek[position];
}
});
However I only get the last item of the array = S.
How can I return all the items individually?
use this
String[] daysOfTheWeek = {"M","T","W","T","F","S","S"};
XAxis xAxis = barChart.getXAxis();
int position = 0;
for(int i =0; i<daysOfTheWeek.length;i++){
position = i;
xAxis.setValueFormatter(new ValueFormatter() { //Returns a string not a list :(
#Override
public String getFormattedValue(float value) {
return daysOfTheWeek[position];
}
}
})
If you want to return the last item of array use this:
return daysOfTheWeek[daysOfTheWeek.length-1];
If you want to get items individually, you could create a method that gets position of item and return that item:
public String getItem(int position)
{
return daysOfTheWeek[position];
}
Silly me, the method accepts a float value. I simply had to use it!
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return daysOfTheWeek[(int)value];
}
});
Try it..
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setValueFormatter(new IndexAxisValueFormatter(getAreaCount));
public ArrayList<String> getAreaCount() {
ArrayList<String> label = new ArrayList<>();
for (int i = 0; i < areaList.size(); i++)
label.add(areaList.get(i).getTopicName());
return label;
}
This trick works 100% for me to display week days from Mo to SU
chartWeeklyDistance.getXAxis().setAxisMinimum(0);
String[] daysOfTheWeek = {"MO", "TU", "WE", "TH", "FR", "SA", "SU"};
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
if (((int) value) > -1 && ((int) value) < 7) {
return daysOfTheWeek[((int) value)];
}
return "";
}
});

Why is my loop not retrieving the last items?

I am trying to implement a method to view a list of items and their quantities, without being repeated. I am doing this using ArrayList which will hold objects of the type Item which I created. The Problem is in the loop where I remove duplicates from the a copy of the original list as it doesn't show the last two Items in the list and I don't know how to fix it. Here is the code. Item is very simple object, it contains (int identifier, int price, String name)
private ArrayList list;
public void print(ListOfItems storeList)
{
list = storeList.getList();
if ( list.size() == 0)
System.out.println("Sorry! There are no available Items at the store at this moment.");
/** I changed this section
else
{
Object[] originalItems = list.toArray();
ArrayList copy = storeList.getCopy(storeList.getList());
Object[] copyItems = copy.toArray();
System.out.println("Here is a list Of available items in this Store");
System.out.println("Name\tIdentifier\tprice\tQuantity");
//this loop is wrong
for (int i = 0; i < originalItems.length-1; i++)
{
for (int j = i+1; j < originalItems.length; j++)
{
if (originalItems[i].equals(originalItems[j]) && copyItems[j] != null)
{
copy.remove(originalItems[j]);
}
}
}
**/
//Below is the write loop
else
{
Object[] originalItems = list.toArray();
ArrayList copy = new ArrayList(list.size());
for (int i = 0; i < originalItems.length; i++)
{
Item item = (Item) originalItems[i];
if (copy.contains(item) == false)
{
copy.add(item);
}
}
Object[]cop = copy.toArray();
for (int i = 0; i < cop.length; i++)
{
if (cop[i] != null)
{
Item item = (Item) copyItems[i];
System.out.print(item.getName() + "\t");
System.out.print(item.getIdentifier() + "\t\t");
System.out.print(item.getPrice() + "\t");
System.out.print(Methods.getOccurences(list, item));
System.out.println();
}
}
System.out.print("*****************************");
}
}
Here is the class for ListOfItems
import java.util.ArrayList;
public class ListOfItems
{
int numOfItemsInStore = 50;
private ArrayList list = new ArrayList(numOfItemsInStore);
public ListOfItems()
{
Item item1 = new Item (111, 50, "Item1");
list.add(item1);
Item item2 = new Item (222, 99, "Item2");
list.add(item2);
Item item3 = new Item (333, 20, "Item3");
list.add(item3);
Item item4 = new Item (444, 199, "Item4");
list.add(item4);
Item item5 = new Item (555, 14, "Item5");
list.add(item5);
Item item6 = new Item (666, 40, "Item6");
list.add(item6);
list.add(item6);
list.add(item6);
list.add(item2);
list.add(item3);
list.add(item3);
list.add(item3);
}
public ArrayList getList()
{
return list;
}
public ArrayList getCopy(ArrayList listToCopy)
{
ArrayList copy = new ArrayList(numOfItemsInStore);
if (listToCopy.isEmpty())
System.out.println("This list is Empty");
else
{
Object[] listArray = listToCopy.toArray();
for (int i = 0; i < listArray.length; i++)
{
Item item = (Item) listArray[i];
copy.add(item);
}
}
return copy;
}
}
here is the Item class
public class Item
{
private int identifier;
private int price;
private String name;
public Item (int id, int price , String name)
{
this.identifier = id;
this.name = name;
this.price = price;
}
public int getIdentifier()
{
return identifier;
}
public int getPrice()
{
return price;
}
public String getName()
{
return name;
}
}
Okay first of all I would suggest to use a Set to remove duplicates...
public void print(ListOfItems storeList)
{
// At this point make sure that "getCopy(ArrayList <Item> listToCopy)" creates a deep copy!
ArrayList <Item> copyOfList = storeList.getCopy(storeList.getList());
// For using this statement make sure that you override "equals" in the "Item" class!
Set <Item> uniqueItems = new HashSet <Item> (copyOfList);
for(Item item : uniqueItems)
{
// Code for usage of each single item
}
}
...This is just one possible approach of solution, but makes sure that you overrides equals and that your function getCopy() creates a deep copy!
Thanks to Coderino Javarino, of course you must override the equals and the hashCode method not the toString method!
One option to override the equals method...
#Override public boolean equals(Object object)
{
if(this == object)
{
return true;
}
if(object == null || getClass() != object.getClass())
{
return false;
}
Item item = (Item) object;
return Objects.equals(this.name, item.name) &&
this.identifier == item.identifier &&
this.price == item.price;
}
And here an option to create a deep copy...
public ArrayList getCopy(ArrayList <Item> listToCopy)
{
if(null == listToCopy)
{
// Handle this option too
}
ArrayList <Item> copy = new ArrayList(listToCopy.size());
for(Item item : listToCopy)
{
// It is important that your class "Item" contains a copy constructor
copy.add(new Item(item));
}
return copy;
}
According to your code, I guess item 6 and item 3 were missed from your final cop list. Because remove action is not correct.
At the begin for-loop, the initial state of 3 variables are:
originalItems: [1,2,3,4,5,6,6,6,2,3,3,3]
copy: [1,2,3,4,5,6,6,6,2,3,3,3]
copyItems: [1,2,3,4,5,6,6,6,2,3,3,3]
The state of 3 variables above after outter for-loop finished round 6 (i=5):
originalItems: [1,2,3,4,5,6,6,6,2,3,3,3]
copy: [1,2,3,4,5,6,2,3,3,3] <- two item 6 were removed, it worked as expect
copyItems: [1,2,3,4,5,6,6,6,2,3,3,3]
Unluckily, when i=6 and j=7, we found that "item 6" is duplicate again, and the copy list removed it. <- the problem is here.
We are absolutely able to explain why "item 3" lost with the same idea. It happened when i=10, j=11.
And how to fix it? If you still want to use 2 for-loop, you can implement the strategy below:
init copy list is empty
init originalitem as copy of your list
for item in originalItem
isExist = false
for copy list
if item in copy
isExist = true
break
if isExist = false
copy add item
But, there are many ways to remove effectively a duplicate element in a list, rather than using 2 for-loop strategy.
else
{
Object[] originalItems = list.toArray();
ArrayList copy = new ArrayList(list.size());
for (int i = 0; i < originalItems.length; i++)
{
Item item = (Item) originalItems[i];
if (copy.contains(item) == false)
{
copy.add(item);
}
}

How to store three different types of items in java collection?

i have a situation where i have to read xml files where i get three elements like this
2019-03-19,null,null
2016-11-30,null,null
2016-10-14,null,null
2016-09-30,null,null
2016-09-30,1,YEARS
2016-09-30,3,MONTHS
2016-09-30,4,MONTHS
I have to store all three items on some data structure and apply my logic like below
I have to find the max of last item and then for that i have to find the max of second item then for that i have to find the max of first element of more than one is present .
Please suggest me some idea
Create a single object like below that can hold all three data elements and is also capable of handling a "null" value for the quantity and term length values. You may want to have the constructor convert the String date (2019-03-19) into a real date object or you could handle that before object creation. Then add these objects to a data structure (i.e. list, etc) that you can use to manage and organize them.
public class ListElement {
public Date date;
public Integer qty;
public String termLength;
public ListElement(Date d, Integer q, String t) {
this.date = d;
this.qty = q;
this.termLength = t
}
// getter methods
public Date getDate() {
return this.date;
}
public Integer getQty() {
return this.qty;
}
public String getTermLength() {
return this.termLength;
}
public toString() {
return System.out.println(this.date + "::" +
this.qty + "::" +
this.termLength)
}
}
You can create an enum if you have some predefined terms:
enum Term {
AGES, YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS;
}
And use it in your class with other two types as:
public class MyObjects {
private Date date;
private Integer quantity;
private Term term;
public MyObjects(Date date, Integer quantity, Term term) {
this.date = date;
this.quantity = quantity;
this.term = term;
}
// getters, setters
}
Then define the constructor that accepts these 3 arguments and use it while processing XML file.
Two different ways to store the data. One is 2D array and the other is arraylist. All the data is type String. You would have to Parse the Integers using Integer.parseInt() to get int value. You will also have to catch for null values. This assumes that your xml data have newline characters at the end of each line.
public static void main(String[] args) {
// TODO code application logic here
//Assuming there are \n char at end of line
String xml = "2019-03-19,null,null\n" +
"2016-11-30,null,null\n" +
"2016-10-14,null,null\n" +
"2016-09-30,null,null\n" +
"2016-09-30,1,YEARS\n" +
"2016-09-30,3,MONTHS\n" +
"2016-09-30,4,MONTHS";
System.out.println("2D Array Output:");
String[][] twoDArrayExample = twoDArrayVersion(xml);
//print 2D array
for(int i = 0; i < twoDArrayExample.length; i++)
{
for(int z = 0; z < twoDArrayExample[i].length; z++)
{
System.out.print(twoDArrayExample[i][z] + " - ");
}
System.out.println();
}
System.out.println("\n\nArray List Output:");
ArrayList<ArrayList<String>> arrayListExample = arrayListVersion(xml);
//print arraylist
for(ArrayList<String> entry : arrayListExample)
{
for(String item : entry)
{
System.out.print(item + " + ");
}
System.out.println();
}
}//end of main
static String[][] twoDArrayVersion(String xml)
{
String[][] dataHolder;
String[] tempDataHolder = xml.split("\n");
dataHolder = new String[tempDataHolder.length][3];
for(int i = 0; i < tempDataHolder.length; i++)
{
String[] tempDataHolder2 = tempDataHolder[i].split(",");
dataHolder[i][0] = tempDataHolder2[0];
dataHolder[i][1] = tempDataHolder2[1];
dataHolder[i][2] = tempDataHolder2[2];
}
return dataHolder;
}
static ArrayList<ArrayList<String>> arrayListVersion(String xml)
{
ArrayList<ArrayList<String>> dataHolder = new ArrayList();
String[] tempDataHolder = xml.split("\n");
for(int i = 0; i < tempDataHolder.length; i++)
{
ArrayList<String> tempArrayList = new ArrayList();
String[] tempDataHolder2 = tempDataHolder[i].split(",");
tempArrayList.add(tempDataHolder2[0]);
tempArrayList.add(tempDataHolder2[1]);
tempArrayList.add(tempDataHolder2[2]);
dataHolder.add(tempArrayList);
}
return dataHolder;
}

Java HashMap custom Object

Example:
d1 = "the sky is blue"
d2 = "the car is blue"
Key Value
the [<d1,1>,<d2,1>]
sky [<d1,1>]
is [<d1,1>,<d2,1>]
blue [<d1,1>,<d2,1>]
car [<d2,1>]
Where:
key = String
ex:
<d1,1>
d1 = Document id
1 = How many times the word apear on file
I created a document type object with the docid variables and frequency.
public class Documento {
private final int docid;
private final int frequencia;
public Documento(int docid, int frequencia) {
this.docid = docid;
this.frequencia = frequencia;
}
public int getDocid() {
return docid;
}
public int getFrequencia() {
return frequencia;
}
#Override
public boolean equals(Object o) {
if ((o instanceof Documento) && docid == ((Documento) o).docid && frequencia == ((Documento) o).frequencia) {
return true;
}
return false;
}
And the dictionary class that is a hashmap with
public class Dicionario {
public Map<String, Documento> indice = new HashMap<>();
public void InsereDicionario(String palavra, int docid) {
int cont = indice.containsKey(palavra) ? indice.get(palavra).getFrequencia() : 0;
indice.put(palavra, new Documento(docid, cont + 1));
}
public int frequencia(String palavra) {
return indice.get(palavra).getFrequencia();
}
public void criaDicionario(String entrada) {
String[] palavras = entrada.split("\\s+");
for (int i = 0; i < palavras.length; i++) {
InsereDicionario(palavras[i], 1);
}
}
public void ListaPalavras(){
for(String key:indice.keySet()){
System.out.println("");
}
}
But what I really need the dictionary is a list of documents , and I do not know how to do this , someone could help me ?
or is there an easier way to do this ?
If you need a list of documents, why not create one? With Java8 this becomes even more convenient:
For example:
public Map<String, List<Documento>> indice = new HashMap<>();
//register new word
indice.putIfAbsent(palavra, new ArrayList<>());
//add additional occurence
indice.get(palavra).add(documento);
//get frequency
int frequencia = indice.get(palavra)
.stream()
.map(d -> d.getFrequencia())
.reduce(0, (s, i) -> s + i);
An alternative would be to use Guava's Multimap, see here
Map<String, List<Documento>>
Obviously you need to adapt the rest of the code.
For example, when you need to add something to the dictionary, if it's the first time you need to create the List with that single document, next time you need to take the already created list and add documents there.

Categories

Resources