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);
// // {李四=[User@6d06d69c], 马六=[User@4e25154f], 张三=[User@15db9742], 王五=[User@7852e922], 钱八=[User@5c647e05], 赵七=[User@70dea4e]}
// ==========================================================================
userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType,LinkedHashMap::new,Collectors.toList()));
System.out.println(userGroupMap);
结果是 按照原来的顺序
{张三=[User@15db9742], 李四=[User@6d06d69c], 王五=[User@7852e922], 马六=[User@4e25154f], 赵七=[User@70dea4e], 钱八=[User@5c647e05]}
//还可以看看这个里面更多一点的 Java 8 Stream Collectors groupingBy 示例:分组、计数、排列
http://www.itdaan.com/blog/2017/06/18/a3c0b00d8ae6ada2238ce732aa1fc0d6.html
}
}
}