Reputation: 352
I have a class as below:
public class Class2 {
private final Integer x;
private final Integer y;
public Class2(final Integer x, Integer y) {
this.x = x;
this.y = y;
}
public Integer getX() {
return x;
}
public Integer getY() {
return y;
}
}
I have a Map object like below:
Map<MyEnum , List<Class2>> mapX
I want to find the sum of x & y members of the Class2 instances in the List instance which is the value item in the above map. I want to use lambda expressions
I have come up with the following incomplete lambda. Thanks in advance.
mapX.entrySet().forEach(entry -> {
System.out.println("MapX-Key : " + entry.getKey() + "\nMapX-Value : "
+ entry.getValue().stream().collect(Collectors.summingInt(???)));
});
Upvotes: 2
Views: 2106
Reputation: 65889
Not quite sure about what you're asking but one of these should help:
// Using Class2
Map<MyEnum , List<Class2>> mapX = null;
mapX.entrySet().forEach(entry -> {
System.out.println("MapX-Key : " + entry.getKey() + "\nMapX-Value : "
+ entry.getValue().stream()
.collect(Collectors.summingInt(x -> x.getX() + x.getY())));
});
// Values from Class2 via Class1
Map<MyEnum , List<Class1>> map1 = null;
map1.entrySet().forEach(entry -> {
System.out.println("MapX-Key : " + entry.getKey() + "\nMapX-Value : "
+ entry.getValue().stream()
.collect(Collectors.summingInt(x -> x.getClass2().getX() + x.getClass2().getY())));
});
Upvotes: 2
Reputation: 54168
You can go this way :
mapX.entrySet().stream()
.map(entry -> "MapX-Key : " + entry.getKey()
+ "\nMapX-Value : "
+ entry.getValue().stream().mapToInt(e -> e.getX() + e.getY()))
.forEach(System.out::println);
This will iterate over each Entry
, then (map
) create a String with the key, and then the sum of x
and y
, and at the end print
them
Upvotes: 2