gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:26:22 27 4
gpt4 key购买 nike

我有 ImmutableTriple 对象的列表,其中第一个和中间可以收集最后一个值(第一个、中间和最后一个是三重值)。现在为了使其可查询,我需要将其转换为 Guava Table 数据结构。我能够使用下面的 for 循环来实现这一点,但我想知道是否可以使用 lambda 表达式更有效地实现这一点。这是片段代码-

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 lambda.
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 类,其中包含一个 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));

关于java - 使用 lambda 将对象列表转换为 Guava Table 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com