Map<Long,String>map=userList.stream().collect(Collectors.toMap(User::getId,User::getName)); 这个获取的就是key为id,value为name的map了。 2. 三个参数的用法 还是沿用上面那个例子,如果这个时候你想获取key是age,value是name的map呢?如果你还是
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())); 关于Coll...
A1 a1_3=newA1(a2_3,"A1_3"); List<A1> list=Arrays.asList(a1_1,a1_2,a1_3);//转换为Map<String,string>,key为A1的ID,value为A2的NAMEMap<String,String> resultMap = list.stream().collect(Collectors.toMap(A1::getID, a1 ->a1.getA2().getNAME()));//输出结果resultMap.forEach((key,...
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())); 关于Co...
这就能证明当出现map的key重复时会报错Duplicate Key的异常了。 如果不想抛异常,自己给传一个新的key值用于替换原有值。 所以, 解决方案一 :给重复的Key设置一个新的值 Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(oldValue, newValue) -> newVal...
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方法转换List,一般会遇到两个问题。一个是转换map,key重复问题;另一个是空指针异常,即转为map的value是null。问题解决!!!一、第一种问题报的错误如下:Duplicate key 原因是声明List集合时,有的值重复,如图: 解决方法:(分三种,具体哪种看业务需求) 1.重复时用后面的value 覆盖前面的valu...
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())); ...
Java8中的Map合并方法 在Java8中,我们可以使用Stream.concat()方法和Collectors.toMap()方法来合并多个Map为一个Map。具体步骤如下: 将多个Map转换为Stream 使用Stream.concat()方法合并这些Stream 使用Collectors.toMap()方法将合并后的Stream转换为一个新的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::new);}public static <T, K, U>Collector...