Understanding Spliterator, Collector and Stream in Java 8

后端 未结 4 1011
栀梦
栀梦 2020-12-12 10:33

I am having trouble understanding the Stream interface in Java 8, especially where it has to do with the Spliterator and Collector interfaces. My problem is that I simply ca

4条回答
  •  Happy的楠姐
    2020-12-12 11:09

    The following are examples of using the predefined collectors to perform common mutable reduction tasks:

     // Accumulate names into a List
     List list = people.stream().map(Person::getName).collect(Collectors.toList());
    
     // Accumulate names into a TreeSet
     Set set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));
    
     // Convert elements to strings and concatenate them, separated by commas
     String joined = things.stream()
                           .map(Object::toString)
                           .collect(Collectors.joining(", "));
    
     // Compute sum of salaries of employee
     int total = employees.stream()
                          .collect(Collectors.summingInt(Employee::getSalary)));
    
     // Group employees by department
     Map> byDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));
    
     // Compute sum of salaries by department
     Map totalByDept
         = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment,
                                                   Collectors.summingInt(Employee::getSalary)));
    
     // Partition students into passing and failing
     Map> passingFailing =
         students.stream()
                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
    

提交回复
热议问题