Examples of Collectors in Java 8 and a brief introduction to Function<T,R&gt

Keywords: Oracle Java

Collectors implements the interface Collector < T, A, R>.
T: The type of element that needs to be reduce d
Dynamic Set Types for A:reduce Operations
Result type of R:reduce operation

  • Give an example

// Collect names into a list

List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

// Collecting names into TreeSet

Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));

// Convert the name to String and connect to a string

String joined = things.stream()
                           .map(Object::toString)
                           .collect(Collectors.joining(", "));

// Calculating the total wages of employees

int total = employees.stream()
                          .collect(Collectors.summingInt(Employee::getSalary)));

// Grouping employees according to department:

Map<Department, List<Employee>> byDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

// Calculating the total wages of employees in different departments

Map<Department, Integer> totalByDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment,
                                                   Collectors.summingInt(Employee::getSalary)));

// Classification of passing and failing students

Map<Boolean, List<Student>> passingFailing =
         students.stream()
                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

For Collectors'official description, see:
Official website documents

If you don't know much about Function interfaces, you can easily make mistakes when using these methods. Here's a brief introduction.

Function<T, R>

Input Types of T-Functions
Output Types of R-Functions

That is, through this function, one type can be converted to another type, such as the following example:

 //Define a function input as a String type, output as an EventInfo type, and EventInfo as a class.           
Function<String, EventInfo> times2 = fun -> { EventInfo a = new EventInfo(); a.setName(fun); return a;};

String[] testintStrings={"1","2","3","4"}; 

//Convert Array of String to map and call times2 function for conversion
Map<String,EventInfo> eventmap1=Stream.of(testintStrings).collect(Collectors.toMap(inputvalue->inputvalue, inputvalue->times2.apply(inputvalue)));

If the transformation process of Collectors.toMap is simple, such as the same input and output types, there is no need to define Function s separately, such as:

Map<String,String> eventmap2=Stream.of(testStrings).collect(Collectors.toMap(inputvalue->inputvalue, inputvalue->(inputvalue+"a")));

Posted by _rhod on Fri, 08 Feb 2019 21:51:17 -0800