Reputation: 103
I have two hash maps: one contains an Integer key and String value.
The other contains an Integer key and float value.
Map<Integer,String> mapA = new HashMap<>();
mapA.put(1, "AS");
mapA.put(2, "Wf");
Map<Integer,Float> mapB = new HashMap<>();
mapB.put(2, 5.0f);
mapB.put(3, 9.0f);
My question is how to compare the two hash maps using the integer key value? I want to print the bitmap value when the key values are the same.
Upvotes: 0
Views: 3911
Reputation: 815
With Java 8 Streams API:
Map<Integer, Object> matchInBothMaps = mapA
.entrySet()
.stream()
.filter(map -> mapB.containsKey(map.getKey()))
.collect(Collectors.toMap(map -> map.getKey(),
map -> map.getValue()));
System.out.println(matchInBothMaps);
Upvotes: 0
Reputation: 103
yes i got solution...
if(mapB.containsKey(position)){
Log.e("bucky",mapB.get(position));}
position means integer value.
Upvotes: 0
Reputation: 49734
If you are allowed to modify mapB
, then the solution is as simple as mapB.keySet().retainAll(mapA.keySet());
.
This will only leave those entries in mapB
that have a corresponding key in mapA
, because the set returned by keySet()
is backed by the map itself, any changes made to it will be reflected to the map.
Upvotes: 0
Reputation: 129
You can just iterate on the keys of mapA
and check if it is present in mapB
then add the value to a third mapC
for example.
Map<String, float> mapC = new HashMap<String, float>();
for (Integer key : mapA.keySet()) {
if (mapB.containsKey(key)) {
mapC.put(mapA.get(key), mapB.get(key));
}
}
Upvotes: 2
Reputation: 1091
Compare keys in two map by using mapB iterator.
Iterator<Entry<Integer, Float>> iterator = mapB.entrySet().iterator();
while(iterator.hasNext()) {
Entry<Integer, Float> entry = iterator.next();
Integer integer = entry.getKey();
if(mapA.containsKey(integer)) {
System.out.println("Float Value : " + entry.getValue());
}
}
Upvotes: 0