如何使用流获取嵌套集合中的所有元素 [英] How to get all elements in nested collection with streams

查看:92
本文介绍了如何使用流获取嵌套集合中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含不同嵌套集合的类,现在我想接收嵌套集合的所有元素,具体来说,我想收集集合的所有StrokePoints.我可以使用旧的" java解决它,但如何使用流来解决呢?

I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

    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的方法.

I am looking for a way to fill the pointList with the stream functionality.

推荐答案

您可以只使用

You can just use Stream.flatMap() twice:

List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

如果需要计算笔画列表,可以将其分为两部分并使用List.size():

If you need to count the strokes list you can split this into two parts and use List.size():

List<Strokes> strokesList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .collect(Collectors.toList());
int strokesCounter = strokesList.size();
List<StrokePoint> pointList = strokesList.stream()
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

或者,您可以在flatMap()中增加AtomicInteger:

Alternatively you can increment an AtomicInteger in flatMap():

final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> {
            List<Strokes> strokes = session.getListOfStrokes();
            strokesCounter.addAndGet(strokes.size());
            return strokes.stream();
        })
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

或使用peek():

final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .peek(i -> strokesCounter.incrementAndGet())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

这篇关于如何使用流获取嵌套集合中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆