java jdk1.8新特性Stream API( 五 )




Integer sum = list.stream().reduce(0, (x, y) -> x + y);


System.out.println(sum);


System.out.println("-------------------------------------------");


Optional<Double> op1 = employees.stream().map(Employee::getSalary).reduce(Double::sum);


System.out.println(op1.get());


}


/**
* 收集 collect —— 将流转换为其它形式 , 领受一个Collector接口的实现 , 用于给Stream中元素做汇总的方式
*/
@Test
public void test2() {
List<String> list = employees.stream().map(Employee::getName).collect(Collectors.toList());


list.forEach(System.out::println);


System.out.println("-----------------------");


Set<String> set = employees.stream().map(Employee::getName).collect(Collectors.toSet());


set.forEach(System.out::println);


System.out.println("-----------------------");


HashSet<String> hashSet = employees.stream().map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));


hashSet.forEach(System.out::println);


}


@Test
public void test3() {
// 总数
Long count = employees.stream().collect(Collectors.counting());
System.out.println(count);


System.out.println("-----------------------");


// 平均值
Double avg = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);


System.out.println("-----------------------");


// 总和
Double sum = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);


System.out.println("-----------------------");


// 最大值
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(max.get());


System.out.println("-----------------------");


// 最大值
Optional<Employee> min = employees.stream()
.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(min.get());


}


// 分组
@Test
public void test4() {
Map<Status, List<Employee>> map = employees.stream().collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);


}


// 多级分组
@Test
public void test5() {
Map<Status, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() < 16) {
return "青年";
} else if (e.getAge() < 18) {
return "中年";
} else {
return "老年";
}
})));


System.out.println(map);


}


// 分区
@Test
public void test6() {
Map<Boolean, List<Employee>> map = employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 5000));


System.out.println(map);


}


@Test
public void test7() {
DoubleSummaryStatistics collect = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));


System.out.println(collect.getAverage());
System.out.println(collect.getCount());

推荐阅读