userList.stream().collect(Collectors.toMap(User::getId, User::getName, (n1, n2)->n1 + n2));// 输出结果:A->张三李四 C->王五 第四个参数(mapSupplier)用于自定义返回 Map 类型,比如我们希望返回的 Map 是根据 Key 排序的,可以使用如下写法: List<User>userList=Lists.newArrayList(newUser().set...
如果我们要求map的顺序要按照list的执行的话,我们就要转map的时候指定map的具体实现。 Map<String, User> maps3 = list.stream().collect (Collectors.toMap(User::getName,Function.identity(),(k1, k2) -> k1,LinkedHashMap::new)); 输出结果 {pangHu=User{name='pangHu', age=18}, piKaQiu=User{name=...
);//使用Stream API将List转换为MapMap<String, String> map =list.stream() .collect(Collectors.toMap(KeyValuePair::getKey, KeyValuePair::getValue));//打印转换后的Mapmap.forEach((key, value) -> System.out.println(key +"->"+value)); }staticclassKeyValuePair {privateString key;privateStrin...
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...
for (User user : userList) { map.put(user.getId(), user.getName()); } 使用Java8 特性 Java8 中新增了Stream特性,使得我们在处理集合操作时更方便了。 以上述例子为例,我们可以一句话搞定: userList.stream().collect(Collectors.toMap(User::getId, User::getName)); ...
userList.stream().collect(Collectors.toMap(User::getId, User::getName)); 当然,如果希望得到 Map 的 value 为对象本身时,可以这样写: userList.stream().collect(Collectors.toMap(User::getId, t -> t)); 或: userList.stream().collect(Collectors.toMap(User::getId, Function.identity())); ...
userList.stream().collect(Collectors.toMap(User::getId, User::getName)); 1. 当然,如果希望得到 Map 的 value 为对象本身时,可以这样写: userList.stream().collect(Collectors.toMap(User::getId, t -> t)); 或: userList.stream().collect(Collectors.toMap(User::getId, Function.identity())); ...
Collectors.toMap 有三个重载方法:toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper); toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction); toMap(Function<? super T...
toMap 使用示例package com.github.mouday.demo; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Demo { public static void main(String[] args) { List<User> users = Arrays.asList( new ...
Collectors.toMap将List转为Map 定义 public final class Collectors { public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::...