我有一个包含不同嵌套集合的类,现在我想接收嵌套集合的所有元素,具体我想收集集合的所有 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)
关于java - 如何使用流获取嵌套集合中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402684/