我有一个包含不同嵌套集合的类,现在我想接收嵌套集合的所有元素,具体我想收集集合的所有 StrokePoints。我可以用“旧”java解决它,但如何用流来解决它?
int strokesCounter = 0;
List<StrokePoint> pointList = new ArrayList<>();
if (!strokesData.getListOfSessions().isEmpty()) {
for (SessionStrokes session : strokesData.getListOfSessions()) {
List<Strokes> strokes = session.getListOfStrokes();
for (Strokes stroke : strokes) {
strokesCounter++;
List<StrokePoint> points = stroke.getListOfStrokePoints();
pointList.addAll(stroke.getListOfStrokePoints());
}
}
}
我正在寻找一种用流功能填充 pointList 的方法。
展平嵌套数据非常简单:
List<StrokePoint> pointList = strokesData.getListOfSessions()
.streams()
.map(SessionStrokes::getListOfStrokes)
.flatMap(List::stream)
.map(Strokes::getListOfStrokePoints)
.flatMap(List::stream)
.collect(Collectors.toList());
沿途收集笔划数比较棘手,而且有些争议。你可以创建一个
AtomicInteger strokesCounter = new AtomicInteger();
并在第一个之后立即增加它flatMap
:
.peek(strokesCounter::incrementAndGet)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)