Java 8: how to 'JOIN' two Maps having the same Keys? [duplicate]
Clash Royale CLAN TAG#URR8PPP
Java 8: how to 'JOIN' two Maps having the same Keys? [duplicate]
This question already has an answer here:
I have two Maps, both sharing the same keys, .
Map<Long/*JOIN.ID*/, Long/*Temp ID*/> tempIDsMap;
Map<Long/*JOIN.ID*/, Long/*Real ID*/> realIDsMap;
What I want to get (maybe using Java 8 Stream API and avoiding loops) is the JOIN of these maps on the JOIN.ID
keys, to get a new Map like below:
JOIN.ID
Map<Long/*Temp ID*/. Long/*Real ID*/> realIDsByTempMap;
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Why not using a loop though?
– Lino
Aug 8 at 8:33
what do you mean by join by key? your maps are
Map<Long, Long>
. So which value is to select in final map(as value can be different for same key)? Do you want to create Map<Long, List<Long>>
?– Shubhendu Pramanik
Aug 8 at 8:38
Map<Long, Long>
Map<Long, List<Long>>
1 Answer
1
Use Collectors.toMap
:
Collectors.toMap
Map<Long,Long> realIDsByTempMap =
tempIDsMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue,
e -> realIDsMap.get(e.getKey())));
Nice, but I bet there is a duplicate for that somewhere. I am just too lazy searching today ;-)
– GhostCat
Aug 8 at 8:34
Here it is: stackoverflow.com/a/24018167/4390212
– DimaSan
Aug 8 at 8:39
@DimaSan Here we close ;-)
– GhostCat
Aug 8 at 8:47
I don't know of any given framework to do that for you, so you have to create your own logic to complete this task. What have you tried so far? Can you provide the code, you have tried? Can you point out specific issues or problems?
– Korashen
Aug 8 at 8:28