Tarun Khaneja Trainee
Tarun Khaneja Trainee

Reputation: 19

GroupBy on ArrayList of HashMap in java

I want to do a "group-by" on arrayList of HashMap Data structure. As my data is not fixed, so I don't have any fixed classes. Data is shown as below.

[{"name":"laxman","state":"Karnataka","Mobile":9034782882}, 
{"name":"rahul","state":"Kerala","Mobile":9034782882}, 
{"name":"laxman","state":"karnataka","Mobile":9034782882}, 
{"name":"ram","state":"delhi","Mobile":9034782882}]

The above keys are not fixed, So, I can't have classes for it. Data and formulas will be dynamical. But for now, I am taking this example to understand Stream.Collector on this data.

Now, I want to get the count on basis of name and state, So basically I want to group-by on name and state and want to get count.

I tried to use Stream.Collector but am not able to achieve what I want.

Upvotes: 0

Views: 1828

Answers (2)

fps
fps

Reputation: 34470

You can accomplish this with Collectors.groupingBy, using a List as the key of the returned Map:

Map<List<String>, Long> result = yourListOfMaps.stream()
    .collect(Collectors.groupingBy(
        m -> Arrays.asList(String.valueOf(m.get("name")), String.valueOf(m.get("state"))),
        Collectors.counting()));

This works well because all implementations of List in Java implement hashCode and equals consistently, which is a must for every class that is to be used as the key of any Map implementation.

Upvotes: 1

Ashraff Ali Wahab
Ashraff Ali Wahab

Reputation: 1108

You have to do groupingBy twice once on the key and once again on the value.

Map<String, Map<Object, Long>> map = listOfMap.stream().flatMap(a -> a.entrySet().stream())
                .collect(Collectors.groupingBy(Map.Entry<String, String>::getKey,
                        Collectors.groupingBy(Map.Entry::getValue, Collectors.counting())));

Output

{mobile={9034782882=4}, name={rahul=1, laxman=2, ram=1}, state={Karnataka=2, delhi=1, Kerala=1}}

Upvotes: 0

Related Questions