Home > Software engineering >  Elegant way of checking list containment using Java streams
Elegant way of checking list containment using Java streams

Time:11-28

I have this list myList of MyObj class which contains an String id field.

I am provided with two id's (String) from the user, and want to validate that myList contains two instances of MyObj corresponding to these provided id's.

What's an elegant way of doing so using streams?

thanks!

CodePudding user response:

How about:

boolean contains = myList.stream()
                         .map(MyObj::getID)
                         .filter(id -> id.equals(id1) || id.equals(id2))
                         .limit(2)
                         .count () == 2;

This is assuming there can be at most one MyObj having id1 and at most one MyObj having id2, which makes sense if these identifiers are unique.

I added the limit(2) in order for the pipeline to stop processing elements once it finds two elements matching the requested identifiers.

  • Related