Pages

Wednesday, July 4, 2018

Java 8 anyMatch(), allMatch(), noneMatch(), findAny() examples

Finding the existence of some elements among a collection of objects after matching with a specific property is common data processing idiom in programming. The Java 8 Streams API provides such facilities through the allMatch, anyMatch, noneMatch, findFirst, and findAny methods of a stream.

Let's take the following class to write example program for each of these methods. This class represents Dish of a menu.

public class Dish {

    private String name;
    private Boolean vegitarian;
    private Integer calaries;
    private Type type;
 
    public Dish(String name, Boolean vegitarian, Integer calaries, Type type) {
       super();
       this.name = name;
       this.vegitarian = vegitarian;
       this.calaries = calaries;
       this.type = type;
    }

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }

    public Boolean getVegitarian() {
       return vegitarian;
    }

    public void setVegitarian(Boolean vegitarian) {
       this.vegitarian = vegitarian;
    }

    public Integer getCalaries() {
       return calaries;
    }

    public void setCalaries(Integer calaries) {
       this.calaries = calaries;
    }

    public Type getType() {
       return type;
    }

    public void setType(Type type) {
       this.type = type;
    }

    public enum Type { MEAT, FISH, OTHER };
}

Using anyMatch() method 

The anyMatch() method accepts a Predicate instance and checks for any matching elements in the stream. This method returns a boolean value, true, if it found a matching, otherwise falseThe anyMatch() method will traverse through the elements of the Stream until it finds a match.

Let's say, we have a  list of Dishes and want to find out if there is any vegetarian Dish among those. Just remind, how did you do this before Java 8. You had to at least write 5 or 6 lines of codes to do the above. In Java 8, you can do this by a single line.

List<Dish> menu = ....
if (menu.stream().anyMatch(Dish::getVegitarian)) {
    System.out.println("The menu is (somewhat) vegetarian friendly!!");
}

Using allMatch() method 

The allMatch() method also accepts a Predicate instance and works similar to anyMatch() method. This method will check to see if all the elements of the stream match the given predicate. For example, you can use it to find out whether the menu is healthy (that is, all dishes are below 1000 calories).

boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);

The allMatch() method stops traversing the elements of the stream as soon as one element produces false output.

Using noneMatch() method

The opposite of allMatch() is noneMatch(). It ensures that no elements in the stream match the given predicate. For example, you could rewrite the previous example as follows using noneMatch.

List<Dish> menu = ....
boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);

Using findAny() method

The findAny() method returns an arbitrary element of the current stream. It can be used in conjunction with other stream operations. For example, you may wish to find a dish that’s vegetarian. You can combine the filter method and findAny to express this query.

List<Dish> menu = .....
Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();

The Optional<T> class (java.util.Optional) is a container class to represent the existence or absence of a value. In the previous code, it’s possible that findAny() doesn’t find any element. Instead of returning null, which is well known for being error prone, the Java 8 introduced Optional.

Optional interface has few important method as follows,

          isPresent() method which returns true if Optional contains a value, false otherwise.
          ifPresent(Consumer<T> block) executes the given block if a value is present.

if (dish.isPresent()) {
 ///........
}

dish.ifPresent(d->System.out.println(d.getName()); 

0 comments:

Post a Comment

Share

Widgets