繁体   English   中英

使用 java 流,将具有相同键但不同值的两个映射合并到一个元组?

[英]Using java streams, merge two maps having same keys but different values to a Tuple?

我有两个具有以下数据类型的地图,

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 流来实现这一点吗?

其他简单的方法是这样的:

stringValues.forEach((key, value) -> {
        Pair<List<String>, List<Boolean>> pair = new Pair<>(value, booleanValues.get(key));
        stringBoolValues.put(key, pair);
});

stringBoolValues = stringValues
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, 
  entry -> new Pair<>(entry.getValue(), booleanValues.get(entry.getKey()))));

尝试这样:

Set<Pair<Long,String>> keys = new HashSet<>(stringValues.keySet());
keys.addAll(booleanValues.keySet());

keys.stream().collect(Collectors.toMap(key -> key, 
           key -> new Pair<>(stringValues.get(key), booleanValues.get(key))));

前提条件:对于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的需要。

假设您的stringValues mapbooleanValues map stringValues map具有一组超级键,则可以解决此问题。

Map<Pair<Long, String>, Pair<List<String>, List<Boolean>>> result = stringValues.entrySet().stream()
    .collect(
        Collectors.toMap(Map.Entry::getKey, 
            m -> new Pair<>(m.getValue(), booleanValues.get(m.getKey()))));

只需使用Collectors.toMapvalueMapper轻松合并两个不同地图中的值:

Map<Pair<Long, String>, Pair<List<String>, List<Boolean>>> stringBoolValues = stringValues.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> new Pair(entry.getValue(), booleanValues.get(entry.getKey()))));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM