I have a large list (about 12,000 objects) of custom Objects inside which I will have to search for a specific Object a number of times. As of now, I am mostly using brute force to find the object, but it becomes extremely slow as the list grows larger. This is how I search as of now:
List<MyObject> objectsToSearch; //List containing about 12000 objects
MyObject objectToCompare = new MyObject("this is a parameter"); //Object to compare with list
for(MyObject compareFrom : objectsToSearch){
if(compareFrom.equals(objectToCompare)){
System.out.println("Object found");
}
}
Surely there must be a better way to achieve this. Increasing performance becomes especially important since I will be needing to perform this operation multiple times.
Despite my research I haven't found any detailed tutorial. How do I achieve this?
Are you sure that you really need a List? It seems that you are just checking the object for presence. If you don't need to keep the order of the objects and if it's sufficient to keep each object only once, consider using a Set instead, most probably HashSet.
Do not forget to implement equals() and hashCode() for the objects you store otherwise HashSet will not work.
Make your class MyObject implement the Comparator and then sort the list using Collections.sort() and then you can apply Collections.binarySearch()
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