First of all, please correct me If I am wrong. I want to find index of Item (i.e String value) from ArrayList<CustomType>
without using For Loop.
POJO:
id;
name;
Code:
ArrayList<POJO> list = new ArrayList<POJO>;
//Lots of data added to these list...
Now I want to find the id of particular name from the arraylist without using below kind of for loop.
String id = null;
// TODO Auto-generated method stub
for (int i = 0; i < list.size(); i++) {
if("ABCD".equalsIgnoreCase(list.get(i).getName())) {
id = list.get(i).getId();
break;
}
}
Ideally I don't want to implement the For loop because in some cases i have 500+ data inside the List and to find index using a For loop is not a good way to do this.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List.
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
The ArrayList class contains the indexOf() method, which returns the index of the first occurrence of a specified element in the array list, or -1 , if the element is not contained in the list.
You can use list.indexOf()
, but in order to make it work, you need to override equals
and hasCode
of your POJO
.
By default, two objects will be considered equal if they have the same reference. You can overwrite equals
to work for your case:
public boolean equals(Object o) {
if (!(o instanceof POJO)) {
return false;
}
POJO other = (POJO) o;
return name.equalsIgnoreCase(other.getName());
}
Overridding equals would suggest you override hashCode
. For example:
public int hashCode() {
return name.hashCode();
}
Finding element in this way where complexity would be give you BIG-O (n). I think if you Map that would gives you better result.
HashMap
would be better choice. - Where Complexity would be O(1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With