lambada可以用Collectors.toMap 很方便的将List
@Test
void testDuplicateKey() {
Map map = listDuplicateKey.stream()
.collect(Collectors.toMap(User::getName, Function.identity(), (oldValue, newValue) -> newValue));
}
但这碰到重复的key只能将新的对象替代,如果要把重复的key变为数组,并不能满足需求,先有代码如下,但这并不够优雅
@Test void testList2Mapv1 Map> map = list.stream().collect(Collectors.toMap(User::getId, e -> new ArrayList<>(Arrays.asList(new User(e.getName(), e.getColor()))), (List oldList, List newList) -> { oldList.addAll(newList); return oldList;}));
那么
Collectors.groupingBy方法派上用场了
list.stream().collect(Collectors.groupingBy(User::getId, Collectors.mapping(Function.identity(), Collectors.toList())));
简洁明了的解决~



