测试功能
public class test {
public static void main(String[] args) {
List<User> userList = getUserList();
//1、分组统计数量
Map<String, Long> collect = userList.stream().collect(Collectors.groupingBy(User::getType,Collectors.counting()));
System.out.println(collect);//{高中=2, 初中=1, 小学=2}
//2、根据分组的key值对结果进行排序、放进另一个map中并输出
Map<String,Long> linkedHashMap=new LinkedHashMap<>();
collect.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).forEachOrdered(e->linkedHashMap.put(e.getKey(),e.getValue()));
System.out.println("测试分组后排序:"+linkedHashMap);//测试分组后排序:{高中=2, 小学=2, 初中=1}
}
}
getUserList方法
public static List<User> getUserList(){
User user1 = new User(1,"张三","小学");
User user2 = new User(2,"李四","小学");
User user3 = new User(3,"王五","初中");
User user4 = new User(4,"马六","高中");
User user5 = new User(5,"赵四","高中");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
return list;
}
测试中的实体对象User
import lombok.Data;
@Data
public class User {
private Integer id;
public String name;
private String add;
private String type;
protected int age;
int gender;
public User(Integer id,String name,String type){
this.id = id;
this.type = type;
this.name = name;
}
}