Friday, November 9, 2018

Java 8 - Streams - Terminal Operations

Greetings!

Terminal operations are used to close the stream and generate a result. This is the last operation in a stream pipeline hence eagerly executed. Can return concrete value types like (Integer, String, List, Optional), primitive value (int, long) or void.

Ex:-
forEach, collect, count, anyMatch, nonMatch, allMatch, findAny, findFirst, reduce, min, max, sum are terminal operations.

Let's use employee data set for all operations.
(Complete code is here)


public class Employee {
    
    enum Gender { MALE, FEMALE };
    
    private String name;
    private int age;
    private Gender gender;
    
    private Employee(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    
    public static Employee newInstance(String name, int age, Gender gender) {
        return new Employee(name, age, gender);
    }

    // getters

}



    private static List<Employee> employees = Arrays.asList(
            Employee.newInstance("Jon", 22, Gender.MALE),
            Employee.newInstance("Arya", 16, Gender.FEMALE),
            Employee.newInstance("Tyrion", 30, Gender.MALE),
            Employee.newInstance("Ghost", 5, Gender.MALE),
            Employee.newInstance("Joffery", 20, Gender.MALE),
            Employee.newInstance("Hound", 35, Gender.MALE),
            Employee.newInstance("Danny", 23, Gender.FEMALE)
    );


forEach()

Perform an action for each element in stream. Return type is void.


employees.stream()
            .filter(employee -> employee.getAge() > 20)
            .forEach(System.out::println);


collect()

Reduce the stream into another container such as collection.


employees.stream()
            .filter(employee -> employee.getAge() > 20)
            .collect(Collectors.toList());


count()

Return the total number of elements in the stream.


long count = employees.stream().count();

System.out.println(count);

long femaleCount = employees.stream()
                             .filter(employee -> Gender.FEMALE.equals(employee.getGender()))
                             .count();

System.out.println(femaleCount);


min()

This is a special reduction operation. This returns the minimum value of the stream by given comparator. This return an Optional value.


Optional<Employee> min = employees.stream()
          .min((e1, e2) -> e1.getAge() - e2.getAge());

System.out.println(min);


max()

Same as min operation, this return maximum value.


Optional<Employee> max = employees.stream()
          .max((e1, e2) -> e1.getAge() - e2.getAge());

System.out.println(max);


allMatch()

Check whether all elements in the stream match the given condition.


boolean allMatch = employees.stream()
                            .allMatch(employee -> Gender.MALE.equals(employee.getGender()));
System.out.println("Are all employees male ? " + allMatch);


anyMatch()

Check whether any of the elements in stream matches the given condition.


boolean anyMatch = employees.stream()
                            .anyMatch(employee -> Gender.FEMALE.equals(employee.getGender()));
System.out.println("Is there any female ? " + anyMatch);


nonMatch()

Return true if no element in stream matches the given condition.


boolean noneMatch = employees.stream()
                            .noneMatch(employee -> employee.getAge() > 50);
System.out.println("Is there no one above 50 ? " + noneMatch);


findAny()

As the name suggest this returns any element from the stream.


Optional<Employee> any = employees.stream().findAny();
System.out.println(any);

Optional<Employee> anyFemale = employees.stream()
        .filter(employee -> Gender.FEMALE.equals(employee.getGender()))
        .findAny();
System.out.println(anyFemale);


findFirst()

This returns the first element in the stream.


Optional<Employee> first = employees.stream().findFirst();
System.out.println(first);

Optional<Employee> firstFemale = employees.stream()
                                            .filter(employee -> Gender.FEMALE.equals(employee.getGender()))
                                            .findFirst();
System.out.println(firstFemale); 



No comments:

Post a Comment