priya
priya

Reputation: 375

How to use peek () with filter () java8?

I have a LinkedHashMap.

sorted:{0=[1, 2], 5=[4, 3], 1=[2, 0, 3], 2=[4, 0, 1], 3=[4, 5, 1], 4=[5, 2, 3]}

I tried filtering the values of each key based on its size. For example for the entry 2=[4, 0, 1], I need to filter the values such that the key should only have values whose size is greater than or equal to (>=) it

Consider 2=[4, 1]: since 0 has only two elements, we remove it. 4 and 1 have three elements which is equal to the size of 2, so we keep it.

The final output should be :

nodes_withHighDegreee :{0=[1, 2], 5=[4, 3], 1=[2, 3], 2=[4, 1], 3=[4, 1], 4=[2, 3]}

I tried :

Map<Integer, List<Integer>> nodes_withHighDegree = sorted.entrySet().stream()
                .peek(e -> e.getValue().filter((a,b)-> map.get(a).size() >= map.get(b).size()))
                .collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), (m0, m1) -> m0.putAll(m1));
System.out.println("After sort" + nodes_withHighDegree);

How to use filter function here?

Upvotes: 2

Views: 1763

Answers (1)

Tunaki
Tunaki

Reputation: 137319

You could do it quite simply using Map.replaceAll. Assuming the data is inside a LinkedHashMap called sorted:

Map<Integer, List<Integer>> filtered = new LinkedHashMap<>(sorted);
filtered.replaceAll((k, v) -> v.stream()
                               .filter(i -> sorted.get(i).size() >= v.size())
                               .collect(Collectors.toList()));

Output:

{0=[1, 2], 5=[4, 3], 1=[2, 3], 2=[4, 1], 3=[4, 1], 4=[2, 3]}

This code creates a copy of the map to hold the filtered instance. Then it replaces each value by filtering it and only keeping the integers whose count have a greater value than the current count.


In your current approach, you are using peek to modify the value which is a bad practice. Quoting from its API note:

This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.

Upvotes: 6

Related Questions