Saturday, December 9, 2017

Java 8 :Collectors


JAVA 8 :COLLECTORS

AVERAGING

public static  Collector averagingInt(ToIntFunction mapper)

Double avgAge = residents
        .stream()
        .collect(Collectors.averagingInt(Person::getAge));
}

public static  Collector averagingLong(ToLongFunction mapper)

Double avgAge = residents
        .stream()
        .collect(Collectors.averagingLong(Person::getAge));
}

public static  Collector averagingDouble(ToDoubleFunction mapper)

Double avgAge = residents
        .stream()
        .collect(Collectors.averagingDouble(Person::getAge));
}

GROUPING
 Map employeeMap
        = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));



GROUPING BY SPECIFYING COLLECTOR
Map employeeMap
    = employeeList.stream()
      .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.toSet()));


PARTITIONING  BY PREDICATE
 Map employeeMap
        = employeeList
          .stream()
          .collect(Collectors.partitioningBy((Employee emp) -> emp.getAge() > 30));
    System.out.println("Employees partitioned based on Predicate - 'age > 30'");


PARTITIONING  BY COLLECTOR AS SECOND PARAMETER
Map employeeMapCount =
     employeeList.stream()
         .collect(Collectors.partitioningBy(
             (Employee emp) -> (emp.getAge() > 30),
             Collectors.counting()
         ));

COLLECTORS/MINBY

Optional minAgeEmp =    
            employeeList.stream()
            .collect(Collectors.minBy(Comparator.comparing(Employee::getAge)));
COLLECTORS/MAXBY

Optional minAgeEmp =    
            employeeList.stream()
            .collect(Collectors.maxBy(Comparator.comparing(Employee::getAge)));
COLLECTORS/JOINING

 Stream.iterate(new Integer(0), (Integer integer) -> integer + 1)
              .limit(5)
              .map(integer -> integer.toString())
              .collect(Collectors.joining());

COLLECTORS/SUMMARIZING(INT/LONG/DOUBLE)
The statistical attributes encapsulated by the summary statistics classes are – count of numeric value derived sum of values minimum value maximum value average of all values

IntSummaryStatistics intSummaryStatistics = employeeList
        .stream()
        .collect(Collectors.summarizingInt(Employee::getAge));

COLLECTION ENHANCEMENTS 
COLLECTION ENHANCEMENTS 


IntSummaryStatistics intSummaryStatistics = employeeList
        .stream()
        .collect(Collectors.summarizingInt(Employee::getAge));

No comments:

Post a Comment