Java-8 – how to filter a list, which is the value of the map entry in Java 8?

I have a map < B, list < a > > I want to filter out some a based on some predicates that depend on the key of the mapping 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 traverse the entryset of the map and create a new map, which contains elements that are multiples of the key of the entry That is, the output should be as follows:

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

Filter predicates test list elements with mapped entry keys How can I do this without modifying the original map?

Solution

This is a way to solve the problem by streaming the entries in the original map and creating a new map using the key and filter list:

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())));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>