想问一个各位大牛技术问题,这个操作用 java8 分组怎么做?

2020-09-23 21:56:59 +08:00
 thatiam92

有一个对象集合 Stream stream = Stream.of(new People("张三","老师"),new People("李四","学生"),new People("王五","校长"));

想通过分组得类似于这样的分组 Map<Boolean,List<People>> ;

当为 true 时,List 集合为 {"张三","李四","王五")

当为 false 时候,list 集合为{"张三老师","李四学生","王五校长"};

2039 次点击
所在节点    Java
5 条回复
lululau
2020-09-23 22:16:33 +08:00
问题描述得一堆错误,尝试理解下你的意图:

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()));
lululau
2020-09-23 22:27:01 +08:00
另外一个思路:

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()))
lululau
2020-09-23 22:28:31 +08:00
更正:

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()))
thatiam92
2020-09-28 09:43:27 +08:00
3q :) 问题虽然描述得不好 <-.->,但根据思路找到了解决办法
siweipancc
2020-09-30 09:46:14 +08:00
peoples.stream().collect(LinkedMultiValueMap::new, (m, p) -> { m.add(true, p.getName());m.add(false, p.getName().concat(p.getPosition())); }, Map::putAll);

为什么会有这种奇葩的玩法 OTZ,不都是映射域值吗。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/709921

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX