
有一个对象集合 Stream stream = Stream.of(new People("张三","老师"),new People("李四","学生"),new People("王五","校长"));
想通过分组得类似于这样的分组 Map<BooleanList<People>> ;
当为 true 时,List 集合为 {"张三","李四","王五")
当为 false 时候,list 集合为{"张三老师","李四学生","王五校长"};
1 lululau 2020 年 9 月 23 日 问题描述得一堆错误,尝试理解下你的意图: var people = List.of(new Person("张三","老师"),new Person("李四","学生"),new Person("王五","校长")); var result = Map.of(true, people.stream().map(Person::getName).collect(Collectors.toList()), false, people.stream().map(Person::getNameWithRole).collect(Collectors.toList())); |
2 lululau 2020 年 9 月 23 日 另外一个思路: var result = people.stream().flatMap(p -> Steam.of(Pair.of(true, p.getName()), Pair.of(false, p.getNameWithRole()))).collect(Collectors.groupingBy(Pair::getLeft, Collectors.mapping(Pair.getRight), Collectors.toList())) |
3 lululau 2020 年 9 月 23 日 更正: var result = people.stream().flatMap(p -> Steam.of(Pair.of(true, p.getName()), Pair.of(false, p.getNameWithRole()))).collect(Collectors.groupingBy(Pair::getLeft, Collectors.mapping(Pair::getRight, Collectors.toList())) |
4 thatiam92 OP 3q :) 问题虽然描述得不好 <-.->,但根据思路找到了解决办法 |
5 siweipancc 2020 年 9 月 30 日 peoples.stream().collect(LinkedMultiValueMap::new, (m, p) -> { m.add(true, p.getName());m.add(false, p.getName().concat(p.getPosition())); }, Map::putAll); 为什么会有这种奇葩的玩法 OTZ,不都是映射域值吗。 |