Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key
若可能出现key
一样的情况,则指定一个覆盖规则(这里是选择第二个key覆盖第一个key):
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
Function接口中的默认方法 Function.identity(),这个方法返回自身对象, user-> user是一个返回本身的lambda表达式
Map<String, User> maps = userList.stream().collect(Collectors.toMap(User::getId, user -> user, (key1, key2) -> key2));
有时候,希望得到的map
的值不是对象,而是对象的某个属性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));