List<String> strList1 = Arrays.asList("aaa", "bbb", "ccc");
List<String> strList2 = Arrays.asList("ddd", "eee", "fff");
List<List<String>> list = Arrays.asList(strList1,strList2);
int noOfElements = (int) list.stream().flatMap(i->i.stream()).count();
System.out.println(noOfElements);我想计算单个Strings的数量(如上面的代码片段中所做的)。我可以在扁平列表之后这样做,但是我想在不使用的情况下使用flatMap()来执行相同的flatMap()。总得有办法才能拿到伯爵。提前谢谢。
发布于 2017-02-21 14:36:49
您可以将单个列表map到他们的size并计算sum
int noOfElements = list.stream().mapToInt(List::size).sum();或者像@MarkusBenko建议的那样使用reduce:
int noOfElements = list.stream().reduce(0, (i, l) -> i + l.size(), (i, j) -> i + j)https://stackoverflow.com/questions/42370194
复制相似问题