Efficiently Comparing Checking Maps inside a list of Objects in Java

Mel :

So, I have an object, that has a hashmap inside it (of course, with the corresponding getter and setter).

public class ObjA {
   private HashMap<String, Boolean> mymap;
   ...
}

Then, I have another class with a list of those objects (and corresponding getters/setters):

public class ObjB {
   private List<ObjA> list;
   ...
}

Then, a third class CheckerClass needs to check how many ObjA in the list inside ObjB have the same map (this means same keys and same values for each key).

My initial thought was: loop the list, and for each ObjA parse its map to a String. Collect all the parsings on a Collection, and then count duplicates. But I want something more memory efficient, and more elegant: you know, easily read. And I'm not sure how to get it.

sprinter :

Here's a way of creating a count of each unique map:

list.stream().collect(Collectors.groupingBy(ObjA::getMyMap, Collectors.counting());

This works because Map.equals does exactly what you want: checks if the keysets are the same and map to equal values.

So then for each unique map you can find the number of times it appears in the list. Or if you specifically want to know how many duplicates there are, then use .values().stream().filter(c -> c > 1).count() on the resulting map.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307240&siteId=1
Recommended