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

Converting List of object to Guava Table data structure using lamda

我有 ImmutableTriple 对象列表,其中 first 和 middle 可以收集最后一个值(first、middle 和 last 是三重值)。 现在为了使其可查询,我需要将其转换为 Guava Table 数据结构。我能够通过下面的 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);
}

有一个 Tables class 包含一个 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));