Scorpion Scorpion - 1 year ago 95
Java Question

Better way to find index of item from ArrayList<CustomObject>

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.

Answer Source

Thank you all for your kind and quick response. But a Special thanks to Joachim Sauer. You are absolutely right that 500 elements is not a lot, chances are this loop has no real effect on the performance of your code (even 'though it is inefficient). Even I try it up to 5000 elements and still there is no negative impact on the performance.

Thank you all once again and thank you for your comment Joachim Sauer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download