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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With