代码之家  ›  专栏  ›  技术社区  ›  Mohammad Adnan Arun

使用lamda将对象列表转换为Guava表数据结构

  •  0
  • Mohammad Adnan Arun  · 技术社区  · 7 年前

    我有一个ImmutableTriple对象列表,其中first和middle可以收集最后的值(first、middle和last是三重值)。 现在为了使其可查询,我需要将其转换为Guava表数据结构。我可以用下面的for循环实现这一点,但我想知道是否可以用lamda表达式在功能上实现这一点。 这是零件代码-

    public static void main(String[] args) {
        //In real world, this list is coming from various transformation of lamda
        final List<ImmutableTriple<LocalDate, Integer, String>> list = ImmutableList.of(
                ImmutableTriple.of(LocalDate.now(), 1, "something"),
                ImmutableTriple.of(LocalDate.now(), 1, "anotherThing")
        );
        Table<LocalDate, Integer, List<String>> table = HashBasedTable.create();
        //is it possible to avoid this forEach and use side effect free lamda.
        list.forEach(s -> {
            final List<String> strings = table.get(s.left, s.middle);
            final List<String> slotList = strings == null ? new ArrayList<>() : strings;
            slotList.add(s.right);
            table.put(s.left, s.middle, slotList);
        });
        System.out.println(table);
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Flown    7 年前

    有一个 Tables 类,其中包含 Collector 以获得您想要的结果。

    Table<LocalDate, Integer, ImmutableList<String>> collect = list.stream()
            .collect(Tables.toTable(
                    it -> it.left,
                    it -> it.middle,
                    it -> ImmutableList.of(it.right),
                    (l1, l2) -> ImmutableList.<String>builder()
                            .addAll(l1).addAll(l2).build(), 
                    HashBasedTable::create));
    

    如果你真的想要一个可变的 List 然后您可以使用:

    Table<LocalDate, Integer, List<String>> collect = list.stream()
            .collect(Tables.toTable(
                    it -> it.left,
                    it -> it.middle,
                    it -> Lists.newArrayList(it.right),
                    (l1, l2) -> {l1.addAll(l2); return l1;},
                    HashBasedTable::create));