简体   繁体   中英

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

I have two maps with the following data type,

Map<Pair<Long,String>, List<String>>  stringValues;
Map<Pair<Long,String>, List<Boolean>>  booleanValues ;

I want to merge the above maps to the following datastructure

Map<Pair<Long,String>, Pair<List<String>,List<Boolean>>>  stringBoolValues;

My input has two maps with same key but different values. I want to group them to a pair. Can I use java stream to achieve this ?

other simple way is like this:

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

Try like this:

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

Precondition: You had overridden equals()/hashCode() properly for 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));

Where Pair.of is:

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

You can even use Map.computeIfAbsent to avoid the need of explicit checking for null.

Assuming your stringValues map has a super set of keys present in booleanValues map this would solve the problem.

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

Just using the valueMapper in Collectors.toMap to merge values in two different maps easily:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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