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

时间:2018-08-23 04:36:21

标签: java java-8 stream java-stream

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

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

4 个答案:

答案 0 :(得分:3)

另一种简单的方法是这样的:

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))));

答案 1 :(得分:1)

前提条件:您已为equals()/hashCode()正确覆盖Pair<Long, String>

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的需要。

答案 2 :(得分:0)

假设您的stringValues mapbooleanValues 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()))));

答案 3 :(得分:0)

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

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()))));