Guava FluentIterable - Get only first object or null from list

by GarciaPL on Tuesday 23 February 2016

A few days ago I had issue, that I need to get first object from some list which meet my requirements. Of course I can create some loop, write some if statement. If I will find interesting me object, then I am gonna return it. If I will not find any useful in whole list, then I am will return null.

Above solution is done in quite old-style approach. Now it is time for functional programming! I found very useful a library called Guava and it's utility class called FluentIterable. It supports you to manipulate Iterable instances in a chained fashion. This class has a lot of functionalities, but I would like to focus only on one case - get first interesting object to my pattern or just return null.

MyClass interestingObjectOrNull = FluentIterable.from(myList)
    .firstMatch(new Predicate<MyClass>() {
      @Override
      public boolean apply(MyClass element) {
        return element.getId == 125L
      }
    })
    .orNull();


And that's it! Simple, isn't ? All you need to remember to check returned object if it is null or not. Of course you might write as much complex apply pattern as you like.
Reference :
[1] Stackoverflow - Get only element of a collection view with Guava, without exception when there are multiple elements
[2] Pastebin - Source code