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

时间:2017-12-08 19:17:24

标签: java java-8 guava

我有ImmutableTriple对象列表,其中第一个和中间可以收集最后一个值(第一个,中间和最后一个是三个值)。  现在为了使其可查询,我需要将其转换为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);
}

1 个答案:

答案 0 :(得分:2)

有一个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));