run_time_error
run_time_error

Reputation: 707

How to filter a List which is a value of a Map entry in java 8?

I have a Map<B, List<A>>. I want to filter out some A based on some predicate which relies on the key of the map entry of type B. For example here is my data structure:

List<Integer> list1 = Arrays.asList(5,2,3,4);
List<Integer> list2 = Arrays.asList(5,6,7,8);
List<Integer> list3 = Arrays.asList(9,10,11,12,13);
List<Integer> list4 = Arrays.asList(11,23,112);
Map<Long, List<Integer>> map = new HashMap<>();
map.putIfAbsent(2L, list1);
map.putIfAbsent(3L, list2);
map.putIfAbsent(4L, list3);
map.putIfAbsent(5L, list4);

Now I want to iterate through the entrySet of the map and make a new map having list containing the elements which is a multiple of the key of that entry. i.e. The output should look like this:

2L --> List of (2, 4)
3L --> List of (6)
4L --> List of (12)
5L --> empty List

The filtering predicate uses the map entry key value to test the list elements. How can I achieve this without modifying the original map ?

Upvotes: 3

Views: 352

Answers (2)

c0der
c0der

Reputation: 18792

Doing it in two steps may make it more readable:

    //create a new map
    Map<Long, List<Integer>> newMap = new HashMap<>();
    //add filtered entries to it
    map.entrySet().forEach(
                           e ->newMap.put( e.getKey(),e.getValue()
                                                       .stream()
                                                       .filter(value -> value % e.getKey() == 0)
                                                       .collect(Collectors.toList()))
                           );                               

Upvotes: 2

Jason
Jason

Reputation: 11832

Here's one way to solve the problem, by streaming the entries in the original map, and creating a new map with the keys and filtered lists:

Map<Long, List<Integer>> newMap = map.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().stream()
                .filter(value -> value % entry.getKey() == 0)
                .collect(Collectors.toList())));

Upvotes: 4

Related Questions