方法定义
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
示例
public class SteamExample {
public static void main(String[] args) {
Person person1 = new Person("1", "a");
Person person2 = new Person("2", "b");
Person person3 = new Person("2", "c");
List<Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
Map<String, String> map =
personList.stream()
.collect(Collectors.toMap(Person::getPid,
Person::getName,
(key1, key2) -> key1));
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
@Data
@AllArgsConstructor public static class Person {
private String pid;
private String name;
}
}
参数说明
keyMapper :
- 用来作为Map key的函数
- Person::getPid
valueMapper
- 用来作为Map Value的函数
- Person::getName
mergeFunction
- 用来处理key冲突的函数
- (key1,key2) -> key1; 冲突时保留第一个key的value
- (key1, key2) -> key1 + "||" + key2; 冲突时,组合两个key的value
运行结果
1: a 2: b //Person2和Person3冲突,保留了Person2 1: a 2: b||c //Person2和Person3冲突,拼接了两个person的值
特别注意
KeyMapper 和 ValuerMapper 不允许存在null
Person person1 = new Person("1", "a"); Person person2 = new Person("2", "b"); Person person3 = new Person("2", null); -------------------------------------------- Exception in thread "main" java.lang.NullPointerException at java.base/java.util.HashMap.merge(HashMap.java:1355)
merge function本身时对两个元素的value进行操作,底层使用了HashMap的merge方法, 会优先判断value是否为空
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null || remappingFunction == null) throw new NullPointerException();
兼容方式
- 进行Map前,过滤掉key/value取值,可能为空的
Map<String, String> map = personList.stream() .filter(p -> StringUtils.hasText(p.getPid()) && StringUtils.hasText(p.getName())) .collect( Collectors.toMap( Person::getPid, Person::getName, (key1, key2) -> key1 + "||" + key2));
本文由 Ivan Dong 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Sep 26, 2023 at 10:19 am