掌握java stream 流集合转Map操作 一、前言 在实际的开发过程中,还有一个使用最频繁的操作就是,将集合元素中某个主键字段作为key,元素作为value,来实现集合转map的需求,这种需求在数据组装方面使用的非常多,尤其是在禁止连表 sql 查询操作的公司,视图数据的拼装只能在代码层面来实现。 二、集合转Map(不分组) 在jd...
map.entrySet().stream().forEach(System.out::println);//转换为TreeMapMap<Integer, Person> treeMap = personList.stream().collect(Collectors.toMap(Person::getId, d->d, (oldValue, newValue)->newValue, TreeMap::new)); System.out.println("treeMap:==="); treeMap.entrySet().stream().for...
@TestpublicvoidshouldReturnMapWhenCollectDuplicateKey() {Map<String,Student> map =fakeStudent().stream().collect(HashMap::new, (m, v) -> m.put(v.getName(), v),HashMap::putAll);assertEquals("{name5=Student [studentNo=null, name=name5, gender=true, age=2], "+"name4=Student [stud...
Map<String,List<String>>map=list.stream().collect(Collectors.toMap(Person::getId,p->{List<String>getNameList=newArrayList<>();getNameList.add(p.getName());returngetNameList;},(List<String>value1,List<String>value2)->{value1.addAll(value2);returnvalue1;}));System.out.println(map); 输...
Map<Integer,String>map=stream.collect(Collectors.toMap(String::length,Function.identity())); 1. 这里的String::length是获取元素的长度作为键,Function.identity()是获取元素本身作为值,你也可以根据需要自定义键和值的获取方法。 总结 通过上述步骤,你可以实现Java Stream流返回Map的功能。记住,Stream提供了丰富...
Map<Long,String>map=userList.stream().collect(Collectors.toMap(User::getId,User::getName)); 这个获取的就是key为id,value为name的map了。 2. 三个参数的用法 还是沿用上面那个例子,如果这个时候你想获取key是age,value是name的map呢?如果你还是沿用上面的方法,就会出问题了,因为有两个age...
Map<Long,String> personIdNameMap = personList.stream().collect(Collectors.toMap(person ->preson.getId(),person ->preson.getName())); 上述的例子,是把personList(人员集合)提取内容,生成Map<人员id,人员名字>。 解析如下: 第一个参数person ->preson.getId()表示选择人员id作为map的key值;...
java8使⽤stream的collect进⾏list转map注意事项1.创建Person类 package com.xkzhangsan.normal.collectors;public class Person { private Integer id;private String name;private Integer score;public Integer getId() { return id;} public void setId(Integer id) { this.id = id;} public String getName...
stream().collect(Collectors.toMap(User::getId, Function.identity())); 方法三 Map<Integer, List<User>> map = list.stream().collect(Collectors.groupingBy(T::getUserId)); 方法四 Map<Integer, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName));...
方法四 Map<Integer,String>map=list.stream().collect(Collectors.toMap(User::getId,User::getName))...