Build a stream in HashMap using Lambda in Java 8

I have a HashMap that I need to filter out with some function:

HashMap<Set<Integer>, Double> container
Map.Entry<Set<Integer>, Double> map = container.entrySet()
            .stream()
            .filter(k -> k.getKey().size() == size)

For size = 2, the following should be true:

containerBeforeFilter = {1,2,3} -> 1.5, {1,2} -> 1.3
containerAfterFilter = {1,2} -> 1.3

After I applied the function in the filter, I want to collect the results again in the HashMap. However, when I try to apply the proposed method here , I get illegal allegations.

Thus, the following statement used after the filter is illegal:

.collect(Collectors.toMap((entry) -> entry.getKey(), (entry) -> entry.getValue()));

What would be the right way to collect unchanged map values, where the only criteria satisfy certain keywords?

UPDATE

The error in the above code is a variable type map. It should be map, not Map.Entry.

Thus, the functional code:

Map<Set<Integer>, Double> map = container.entrySet()
            .stream()
            .filter(k -> k.getKey().size() == size)
            .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
+4
2

, Collectors.toMap stream.collect Map<Object,Object>.

:

Map<Set<Integer>, Double> result = new HashMap<>();
container.entrySet()
    .stream()
    .filter(entry -> entry.getKey().size() == size)
    .forEach(entry -> result.put(entry.getKey(), entry.getValue()));
+3

.

"- > ". "-" " > ".

+2

Source: https://habr.com/ru/post/1615017/


All Articles