1、根据列表中实体字段与实体的映射Map
//不建议使用 因为key重复的话,Collectors.toMap报错 :Duplicate key
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
//推荐 mergeFuction参数,遇到重复key时,可以选择第一个或者最后一个作为value
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
2、有时候,希望得到的map的值不是对象,而是对象的某个属性
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
3、List 以ID分组 Map<Integer,List>
Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
System.err.println(“groupBy:”+groupBy);
输出:
{1=[Apple{id=1, name=‘苹果1’, money=3.25, num=10}, Apple{id=1, name=‘苹果2’, money=1.35, num=20}], 2=[Apple{id=2, name=‘香蕉’, money=2.89, num=30}], 3=[Apple{id=3, name=‘荔枝’, money=9.99, num=40}]}
4、List里的对象不是实体而是Map键值对的情况
Map<String,String> map= list.stream().collect(Collectors.toMap(s->s.get(“main_member”),s->s.get(“data_date”)));