简体   繁体   中英

Comparing two hash-maps and printing intersections

I have two hash maps: one contains an Integer key and String value.

The other contains an Integer key and float value.

Code

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.

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));
    }
}

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());
        }
    }

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.

yes i got solution...

 if(mapB.containsKey(position)){
          Log.e("bucky",mapB.get(position));}

position means integer value.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM