As your list is an ArrayList
, it can be assumed that it is unsorted. Therefore, there is no way to search for your element that is faster than O(n).
If you can, you should think about changing your list into a Set
(with HashSet
as implementation) with a specific Comparator
for your sample class.
Another possibility would be to use a HashMap
. You can add your data as Sample
(please start class names with an uppercase letter) and use the string you want to search for as key. Then you could simply use
Sample samp = myMap.get(myKey);
If there can be multiple samples per key, use Map<String, List<Sample>>
, otherwise use Map<String, Sample>
. If you use multiple keys, you will have to create multiple maps that hold the same dataset. As they all point to the same objects, space shouldn't be that much of a problem.