Reputation: 2083
I have two hashmaps:
Map<String, String> mapA = new HashMap<String, String>();
Map<String, String> mapB = new HashMap<String, String>();
TreeSet<String> uniquekeys = new TreeSet<String>();
mapA.put("1","value1");
mapA.put("2","value2");
mapA.put("3","value3");
mapA.put("4","value4");
mapA.put("5","value5");
mapA.put("6","value6");
mapA.put("7","value7");
mapA.put("8","value8");
mapA.put("9","value9");
mapB.put("1","value1");
mapB.put("2","value2");
mapB.put("3","value3");
mapB.put("4","value4");
mapB.put("5","value5");
To get the common key value pairs from the two hashmaps, I have written the below logic:
uniquekeys.addAll(mapA.keySet());
uniquekeys.addAll(mapB.keySet());
and then use the keys from the treeset: uniquekeys
to retrieve unique key value pairs from mapA & mapB.
But this is not giving me the details of all the keys from mapA. I understand this way is flawed but I couldn't come up with a proper logic.
Could anyone let me know how can I retrieve key value pairs that are common in mapA and mapB into a new HashMap ?
Upvotes: 2
Views: 2428
Reputation: 9786
You can do it with Java 8 Streams in the following way:
Map<String, String> commonMap = mapA.entrySet().stream()
.filter(x -> mapB.containsKey(x.getKey()))
.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
Upvotes: 2
Reputation: 138
Use Guava Util Sets
Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);
Upvotes: 0
Reputation: 1082
Instead of adding all keys to a TreeSet, you can fill the TreeSet with common values:
uniquekeys.addAll(mapA.keySet());
uniquekeys.retainAll(mapB.keySet());
This way, the keys contained in A but not B will be removed. Know you've got your TreeSet, you can do what you want.
However, you can also create your HashMap without TreeSet, as @Ramesh and @NiVeR suggest
Upvotes: 0
Reputation: 340
Try below logic :
Map<String, String> common = new HashMap<String, String>();
for(String key : mapA.keySet()) {
if(mapB.get(key) !=null ) {
if(mapA.get(key).equals(mapB.get(key))) {
common.put(key, mapA.get(key));
}
}
}
Upvotes: 2