Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 694
Raghavan Avatar asked Jul 09 '26 21:07

Raghavan


2 Answers

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))));
like image 165
Hadi J Avatar answered Jul 11 '26 12:07

Hadi J


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.

like image 20
Mạnh Quyết Nguyễn Avatar answered Jul 11 '26 12:07

Mạnh Quyết Nguyễn