Map<Long, User> map = userList.stream().collect(Collectors.toMap(User::getId, p -> p));这一步就是将userList 转换为key为id,value为User对象的map。 User::getId ===》 User对象的getId方法 p -> p ===》就是进来的是什么,最终就是什么,这里就是进来的是User对象,出去的也就是User...
定义 publicfinalclassCollectors{publicstatic<T,K,U>Collector<T,?,Map<K,U>>toMap(Function<?superT,?extendsK>keyMapper,Function<?superT,?extendsU>valueMapper){returntoMap(keyMapper,valueMapper,throwingMerger(),HashMap::new);}publicstatic<T,K,U>Collector<T,?,Map<K,U>>toMap(Function<?superT,...
前面已经说过Stream背后依赖于某种数据源,数据源可以是数组、容器等,但不能是Map。反过来从Stream生成Map是可以的,但我们要想清楚Map的key和value分别代表什么,根本原因是我们要想清楚要干什么。通常在三种情况下collect()的结果会是Map: 使用Collectors.toMap()生成的收集器,用户需要指定如何生成Map的key和value。 使...
Map<Long,Integer> map8 = userList.stream().collect(Collectors.toMap(it -> it.getId(), it -> it.getAge());//或着:Map<Long,Integer> map9 = userList.stream().collect(Collectors.toMap(UserInfoDetailVo::getId, UserInfoDetailVo::getAge));//对map的key添加具体业务,对map的value添加具体业务...
Stream(流)是一个来自数据源的元素队列并支持聚合操作; map map 方法用于映射每个元素到对应的结果; Collectors Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串。 使用方式: 1.首先创建一个实体类,添加部分属性; ...
===//Map<String,String> 即 id->name//串行收集Stream.of(studentA,studentB,studentC).collect(Collectors.toMap(Student::getId,Student::getName));//并发收集Stream.of(studentA,studentB,studentC).parallel().collect(Collectors.toConcurrentMap(Student::getId,Student::getName)); 那么如果key重复的该...
Map<Integer,Set<String>> collect = servers.stream.collect(Collectors.groupingBy(String::length, mapSupplier, Collectors.toSet())); 这就非常好办了,我们提供一个同步Map不就行了,于是问题解决了: Supplier<Map<Integer, Set<String>>> mapSupplier = () -> Collections.synchronizedMap(new HashMap<>()...
有时候使用Java8 新特性stream流特性是,需要返回Map集合,实现例子如下: Map<Long,String> personIdNameMap = personList.stream().collect(Collectors.toMap(person ->preson.getId(),person ->preson.getName())); 上述的例子,是把personList(人员集合)提取内容,生成Map<人员id,人员名字>。
Map<Long,UserInfoDetailVo> map5 = userList.stream().collect(Collectors.toMap(it -> { //可添加具体业务,需要return map的key return it.getId() + 1; }, Function.identity())); 1. 2. 3. 4. (2)对map的value添加具体业务 Map<Long,UserInfoDetailVo> map6 = userList.stream().collect(Colle...
Java8 中新增了 Stream 特性,使得我们在处理集合操作时更方便了。以上述例子为例,我们可以一句话搞定:userList.stream().collect(Collectors.toMap(User::getId, User::getName));当然,如果希望得到 Map 的 value 为对象本身时,可以这样写:userList.stream().collect(Collectors.toMap(User::getId, t -> t))...