How to compare two maps and bring the results in new map

37 Views Asked by At

I have one Map

Map<Long, List<Set<Long>>> map1; Example: Map<City_Id, List<Set<Subtier_Cities_ids>>> 

There is Another Map `

Map<Long, Set<Long>> map2; Example: Map<Subtier_Cities_ids,Set<Villages_ids>>`

I want to compare the values of map1 (Second value in the list) and the keys of map2 and bring new map

Map<Long, Set<Long>> map3; Example: Map<City_Id, Set<Villages_ids>>
1

There are 1 best solutions below

1
On BEST ANSWER

You can achieve this by iterating over the entry of map1 and then iterating over the list of Sets. If I understood correctly code should look like this:

Map<Long, List<Set<Long>>> map1 = ...; // Your map1
Map<Long, Set<Long>> map2 = ...; // Your map2
Map<Long, Set<Long>> map3 = new HashMap<>(); // Your map3

for (Map.Entry<Long, List<Set<Long>>> entry : map1.entrySet()) {
    Long cityId = entry.getKey();
    List<Set<Long>> sets = entry.getValue();
    Set<Long> villages = new HashSet<>();

    for (Set<Long> subTierCities : sets) {
        for (Long subTierCity : subTierCities) {
            Set<Long> villageSet = map2.get(subTierCity);
            if (villageSet != null) {
                villages.addAll(villageSet);
            }
        }
    }

    map3.put(cityId, villages);
}