你们能帮我如何得到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));