Skip to main content

How can I find elements by value in a collection

In this Q&A, we'll go over the different APIs provided by the collection classes to find elements by value.

One straight forward way is to iterate over a Collection to find elements by value or based on a predicate.

List interface provides couple of methods - contains and indexOf - to find elements.  See below code snippet for usage details.

List<Integer> l = new ArrayList<>();
IntStream.range(0,100).forEach((i)->l.add(i));
boolean b = l.contains(10);
assertEquals("list contains 10", true, b );

b = l.contains(100);
assertEquals("", false, b );
int idx = l.indexOf(10);
assertEquals("index of 10 is 9", 10, idx );

Stream APIs provide find methods findAny and findFirst which can be used after applying a Predicate.

Optional<Integer> o = l.stream().filter((i)-> i == 10).findAny();
b = o.isPresent();
assertEquals("Found element 10", true, b );

Collections classes provide methods to perform binarySearch on an ordered collection.  Check out this article for more details

Map and Set interfaces provide methods to lookup based on a key.

On top of that NavigableMap interface provides methods to find element lesser than, less than equal to, greater than, greater than equal to the given value. See code snippet below
ConcurrentSkipListMap<Integer, Integer > csm = new ConcurrentSkipListMap<>();
IntStream.range(0,100).forEach((i)->csm.put(i,i));
Map.Entry<Integer, Integer> e = csm.floorEntry(100);
assertEquals("", 99, e.getKey().intValue() );
e = csm.floorEntry(90);
assertEquals("", 90, e.getKey().intValue() );

e = csm.ceilingEntry(-1);
assertEquals("", 0, e.getKey().intValue() );
e = csm.ceilingEntry(90);
assertEquals("", 90, e.getKey().intValue() );

e = csm.higherEntry(10);
assertEquals("", 11, e.getKey().intValue() );

e = csm.lowerEntry(10);
assertEquals("", 9, e.getKey().intValue() );

Comments