How to use the lambda function in Java to sum the list of each column and row?
•
Java
I have a list like this:
List<List<Wrapper>> listOfLists = new ArrayList<>(); class Wrapper { private int value = 0; public int getValue() { return value; } }
It looks like this:
[ [Wrapper(3),Wrapper(4),Wrapper(5)],[Wrapper(1),Wrapper(2),Wrapper(9)],[Wrapper(4),Wrapper(10),Wrapper(11)],]
Is there a concise way to flatten the list by using the lambda function in Java 8, as follows:
(per column): [Wrapper(8),Wrapper(16),Wrapper(25)] (per row): [Wrapper(12),Wrapper(12),Wrapper(25)]
Maybe it can use internal lists of different sizes:
[ [Wrapper(3),[Wrapper(4)],]
This will result in:
(per column): [Wrapper(8),Wrapper(7),Wrapper(9)] (per row): [Wrapper(8),Wrapper(11),Wrapper(4)]
It seems more complicated than turn a list of lists into a list using Lambdas and 3 ways to flat a list of lists Is there a reason to prefer one of them?
My initial approach was similar to the list: https://stackoverflow.com/a/36878011/986160
thank you!
Solution
Each line is actually very simple:
List<Wrapper> perRow = listOfLists.stream() .map(x -> x.stream().mapToInt(Wrapper::getValue).sum()) .map(Wrapper::new) .collect(Collectors.toList());
On the other hand, each column is not that simple:
private static List<Wrapper> perColumn(List<List<Wrapper>> listOfList) { int depth = listOfList.size(); int max = listOfList.stream().map(List::size).max(Comparator.naturalOrder()).get(); return IntStream.range(0,max) .map(x -> IntStream.range(0,depth) .map(y -> listOfList.get(y).size() < y ? 0 : listOfList.get(y).get(x).getValue()) .sum()) .mapToObj(Wrapper::new) .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
二维码