我有两个具有以下数据类型的映射,
Map<Pair<Long,String>, List<String>> stringValues;
Map<Pair<Long,String>, List<Boolean>> booleanValues ;
我想将上面的映射合并到下面的数据结构中
Map<Pair<Long,String>, Pair<List<String>,List<Boolean>>> stringBoolValues;
我的输入有两个映射,它们具有相同的键但不同的值。我想把它们分组成一对。我可以使用java stream来实现这一点吗?
发布于 2018-08-23 12:53:18
前提条件:您已经为Pair<Long, String>
正确覆盖了equals()/hashCode()
Map<Pair<Long,String>, Pair<List<String>,List<Boolean>>> stringBoolValues
= Stream.of(stringValues.keySet(),booleanValues.keySet())
.flatMap(Set::stream)
.map(k -> new SimpleEntry<>(k, Pair.of(stringValues.get(k), booleanValues.get(k)))
.collect(toMap(Entry::getKey, Entry::getValue));
其中,Pair.of
是:
public static Pair<List<String>,List<Boolean>> of(List<String> strs, List<Boolean> bls) {
List<String> left = Optional.ofNullable(strs).orElseGet(ArrayList::new);
List<Boolean> right = Optional.ofNullable(bls).orElseGet(ArrayList::new);
return new Pair<>(left, right);
}
您甚至可以使用Map.computeIfAbsent来避免显式地检查null。
https://stackoverflow.com/questions/51978383
复制相似问题