Java8 stream 之groupingBy() 分組後的排序問題
package com.yeejoin.amos.test.search;
public class User{ private Integer id; private String type; private String name; public User(){} public User(Integer id,String type,String name){ this.id = id; this.type = type; this.name = name; } public void setId(Integer id){ this.id = id; } public Integer getId(){ return id; } public void setType(String type){ this.type = type; } public String getType(){ return type; } public void setName(String name){ this.name = name; } public String getName(){ return name; }
}
package com.yeejoin.amos.test.search;
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
public class MainUser { public static List<User> getUserList() { User user1 = new User(1, "張三", "小學"); User user2 = new User(2, "李四", "小學"); User user3 = new User(3, "王五", "初中"); User user4 = new User(3, "馬六", "高中"); User user5 = new User(5, "趙七", "高中"); User user6 = new User(6, "錢八", "高中");
List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); list.add(user6);
return list; } public static void main(String[] args) { List<User> list = getUserList(); Map<String, List<User>> userGroupMap = new LinkedHashMap<>(); List<User> llist;
//結果是 無序的 userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType)); System.out.println(userGroupMap);
// // {李四=[[email protected]], 馬六=[[email protected]], 張三=[[email protected]], 王五=[[email protected]], 錢八=[[email protected]], 趙七=[[email protected]]} // ========================================================================== userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType,LinkedHashMap::new,Collectors.toList())); System.out.println(userGroupMap);
結果是 按照原來的順序 {張三=[[email protected]], 李四=[[email protected]], 王五=[[email protected]], 馬六=[[email protected]], 趙七=[[email protected]], 錢八=[[email protected]]} //還可以看看這個裡面更多一點的 Java 8 Stream Collectors groupingBy 示例:分組、計數、排列
}