V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
thatiam92
V2EX  ›  Java

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

  •  
  •   thatiam92 · 2020-09-23 21:56:59 +08:00 · 2011 次点击
    这是一个创建于 1317 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

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

    5 条回复    2020-09-30 09:46:14 +08:00
    lululau
        1
    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
        2
    lululau  
       2020-09-23 22:27:01 +08:00   ❤️ 1
    另外一个思路:

    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
        3
    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
        4
    thatiam92  
    OP
       2020-09-28 09:43:27 +08:00
    3q :) 问题虽然描述得不好 <-.->,但根据思路找到了解决办法
    siweipancc
        5
    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,不都是映射域值吗。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1811 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:49 · PVG 08:49 · LAX 17:49 · JFK 20:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.