thatiam92
V2EX  ›  Java

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

  •  
  •   thatiam92 · Sep 23, 2020 · 3263 views
    This topic created in 2237 days ago, the information mentioned may be changed or developed.

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

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

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

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

    5 replies  •  2020-09-30 09:46:14 +08:00
    lululau
    lululau
    Sep 23, 2020
    1
    问题描述得一堆错误,尝试理解下你的意图:

    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
    lululau
    Sep 23, 2020❤️1
    2
    另外一个思路:

    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
    lululau
    Sep 23, 2020
    3
    更正:

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

    为什么会有这种奇葩的玩法 OTZ,不都是映射域值吗。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4534 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:29 · PVG 10:29 · LAX 18:29 · JFK 21:29
    ♥ Do have faith in what you're doing.