我有一个包含不同嵌套集合的类,现在我想接收嵌套集合的所有元素,具体来说,我想收集集合的所有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)

09-12 03:09