A
A
Alex Fox2020-06-22 00:50:09
Java
Alex Fox, 2020-06-22 00:50:09

How to properly iterate over nested Java Maps?

Hello. There is a list of User(name, age, departmant, position, salary) objects that need to be grouped
by fields, let's say name, departmant, position, salary.
Grouping is done like this

Map<String, Map<String, Map<String, Map<String, List<User>>>>> collect = listUsers.stream()
                                .collect(groupingBy(User::getDepartmant,
                                        groupingBy(User::getPosition,
                                                groupingBy(User::getName,
                                                        groupingBy(User::getSalary)))));

You need to access the List and then work with it.
I do so
collect.values().stream()
                                .flatMap(hm -> hm.values().stream())
                                .flatMap(hm -> hm.values().stream())
                                .flatMap(hm -> hm.values().stream())
                                .filter(users -> /*condition*/)

Is this approach correct, or is there a clearer / easier / correct one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Neonoviiwolf, 2020-06-22
@Neonoviiwolf

This is trash, create a class - an entity that will store the necessary data and you can make a list or a map or something like that from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question