gpt4 book ai didi

java - 如何从 lambda 表达式返回新的非抽象 Map?

转载 作者:行者123 更新时间:2023-11-29 04:27:19 24 4
gpt4 key购买 nike

你们能帮我看看如何得到 List<Map<Long, MapDifference> 的结果吗?而不是 List<AbstractMap.SimpleEntry<Long, MapDifference>>

输入是列表。对象有 id 和两个不同的列表对象 - 左和右。我想比较它们并将差异与 id 相关联。然后返回带有 id

的整个 MapDifferences 列表

我有以下代码:

List<AbstractMap.SimpleEntry<Long, MapDifference>> mapDifferences = input
.stream()
.map(h -> {
Optional<Map<String, List<String>>> left = Optional.ofNullable(..Object1.);
Optional<Map<String, List<String>>> right = Optional.ofNullable(..Object2..);
MapDifference mapDifference = Maps.difference(left.orElseGet(LinkedTreeMap::new), right.orElseGet(LinkedTreeMap::new));
return new AbstractMap.SimpleEntry<Long, MapDifference>((long) h.get("property"), mapDifference);
})
.collect(Collectors.toList());

最佳答案

首先 Optional::ofNullable 不应该被用来做一个简单的 null 检查。

接下来您可以使用 Collections::singletonMap 并且您的代码如下所示:

List<Map<Long, MapDifference>> mapDifferences = input
.stream()
.map(h -> {
Map<String, List<String>> left = object1 == null ? new LinkedTreeMap<>() : object1;
Map<String, List<String>> right = object2 == null ? new LinkedTreeMap<>() : object2;
MapDifference mapDifference = Maps.difference(left, right);
return Collections.singletonMap((long) h.get("property"), mapDifference);
})
.collect(Collectors.toList());

或者如果你想扁平化你的结构并且只有唯一的 property 数字,那么使用:

Map<Long, MapDifference> mapDifferences = input
.stream()
.map(h -> {
Map<String, List<String>> left = object1 == null ? new LinkedTreeMap<>() : object1;
Map<String, List<String>> right = object2 == null ? new LinkedTreeMap<>() : object2;
MapDifference mapDifference = Maps.difference(left, right);
return new AbstractMap.SimpleEntry<>((long) h.get("property"), mapDifference);
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

关于java - 如何从 lambda 表达式返回新的非抽象 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601606/

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