您的位置:首页 > 编程语言 > Java开发

java8特性:Collectors.groupingBy进行分组、排序等操作

2017-11-20 19:57 357 查看
  本篇是对博文进行汇总和拓展。

假设已有实体类

public class Student{
private Integer id;
private String name;
...
}


重点1:Collectors类里边相关函数

重点2:collect函数

稍后进行源码分析

1.相关测试代码

package javaX.util.function;

import javaX.Model.Student;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author dugenkui
*         on 2017/11/20.
*/
public class FunctionX {
public static void main(String[] args) {
//1.分组计数
List<Student> list1= Arrays.asList(
new Student(1,"one","zhao"),new Student(2,"one","qian"),new Student(3,"two","sun"));
//1.1根据某个属性分组计数
Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));
System.out.println(result1);
//1.2根据整个实体对象分组计数,当其为String时常使用
Map<Student,Long> result2=list1.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

4000
System.out.println(result2);
//1.3根据分组的key值对结果进行排序、放进另一个map中并输出
Map<String,Long> xMap=new HashMap<>();
result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效
.forEachOrdered(x->xMap.put(x.getKey(),x.getValue()));
System.out.println(xMap);

//2.分组,并统计其中一个属性值得sum或者avg:id总和
Map<String,Integer> result3=list1.stream().collect(
Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId))
);
System.out.println(result3);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 函数 源码