我有一个这样的列表列表:
List<List<Wrapper>> listofLists = new ArrayList<>();
class Wrapper {
private int value = 0;
public int getValue() {
return value;
}
}
看起来像这样:
[ [Wrapper(3),Wrapper(4),Wrapper(5)],[Wrapper(1),Wrapper(2),Wrapper(9)],[Wrapper(4),Wrapper(10),Wrapper(11)],]
有没有一种简洁的方法来使用Java 8中的lambda函数来展平这个列表列表,如下所示:
(per column): [Wrapper(8),Wrapper(16),Wrapper(25)] (per row): [Wrapper(12),Wrapper(12),Wrapper(25)]
可能它可以使用不同大小的内部列表:
[ [Wrapper(3),[Wrapper(4)],]
这将导致:
(per column): [Wrapper(8),Wrapper(7),Wrapper(9)] (per row): [Wrapper(8),Wrapper(11),Wrapper(4)]
它似乎比以下更复杂:
Turn a List of Lists into a List Using Lambdas
和
3 ways to flatten a list of lists. Is there a reason to prefer one of them?
我最初的做法与列表类似:
https://stackoverflow.com/a/36878011/986160
谢谢!
解决方法
每行实际上非常简单:
List<Wrapper> perRow = listofLists.stream()
.map(x -> x.stream().mapToInt(Wrapper::getValue).sum())
.map(Wrapper::new)
.collect(Collectors.toList());
另一方面,每列不是那么简单:
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());
}