如何使用流获取嵌套集合中的所有元素

时间:2019-05-31 23:27:04

标签: java java-stream

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

4 个答案:

答案 0 :(得分:2)

整理嵌套数据非常简单:

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)

答案 1 :(得分:2)

您只能使用Stream.flatMap()两次:

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

如果需要计算笔画列表,可以将其分为两部分并使用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());

或者,您可以在AtomicInteger中增加一个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());

答案 2 :(得分:1)

由于主要目的是解决收集List<StrokePoint>的问题,因此您可以使用flatMap操作执行以下操作:

List<StrokePoint> points = strokesData.getListOfSessions()
        .stream()
        .flatMap(ss -> ss.getListOfStrokes().stream()
                .flatMap(s -> s.getListOfStrokePoints().stream()))
        .collect(Collectors.toList());

此外,Stroke的数量也可以使用流通过将列表的大小总和计算为:

long strokeCount = strokesData.getListOfSessions()
        .stream()
        .mapToLong(ss -> ss.getListOfStrokes().size())
        .sum();

要合并这些操作,可以构造一个AbstractMap.SimpleEntry,同时将条目减少为:

AbstractMap.SimpleEntry<Integer, Stream<StrokePoint>> reduce = strokesData.getListOfSessions()
        .stream()
        .map(ss -> new AbstractMap.SimpleEntry<>(ss.getListOfStrokes().size(),
                ss.getListOfStrokes()
                        .stream()
                        .flatMap(s -> s.getListOfStrokePoints().stream())))
        .reduce(new AbstractMap.SimpleEntry<>(1, Stream.empty()),
                (e1, e2) -> new AbstractMap.SimpleEntry<>(
                        Integer.sum(e1.getKey(), e2.getKey()),
                        Stream.concat(e1.getValue(), e2.getValue())));

使用该条目,您可以获得Stroke的数量和StrokePoint的列表,如下所示:

long strokeCount = reduce.getKey();
List<StrokePoint> strokePoints = reduce.getValue().collect(Collectors.toList());

答案 3 :(得分:0)

如果您担心副作用,可以这样做(但是在撰写本文时,其他两个答案的可读性都非常高):

    Entry<Integer, List<StrokePoint>> summary = //
            strokesData.getListOfSessions()
                       .stream()
                       .flatMap(session -> session.getListOfStrokes().stream())
                       .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                       .reduce((l1, l2) -> {
                           int count = l1.getKey() + l2.getKey();

                           List<StrokePoint> list = l1.getValue();
                           list.addAll(l2.getValue());

                           return new SimpleEntry<>(count, list);
                       })
                       .orElse(new SimpleEntry<>(0, Collections.emptyList()));

    strokesCounter = summary.getKey();
    pointList = summary.getValue();

编辑以添加验证:

public class Scratch {
    public static void main(String[] args) {
        int strokesCounter = 0;
        List<StrokePoint> pointList = new ArrayList<>();
        StrokesData strokesData = new StrokesData();

        SessionStrokes sessionStrokes = new SessionStrokes();
        strokesData.sessionStrokes.add(sessionStrokes);

        Strokes s1 = new Strokes();
        sessionStrokes.strokesList.add(s1);

        s1.strokePoints.add(new StrokePoint());
        s1.strokePoints.add(new StrokePoint());

        Strokes s2 = new Strokes();
        sessionStrokes.strokesList.add(s2);

        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());

        Entry<Integer, List<StrokePoint>> summary = //
                strokesData.getListOfSessions()
                           .stream()
                           .flatMap(session -> session.getListOfStrokes()
                                                      .stream())
                           .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                           .reduce((l1, l2) -> {
                               int count = l1.getKey() + l2.getKey();

                               List<StrokePoint> list = l1.getValue();
                               list.addAll(l2.getValue());

                               return new SimpleEntry<>(count, list);
                           })
                           .orElse(new SimpleEntry<>(0, Collections.emptyList()));

        strokesCounter = summary.getKey();
        pointList = summary.getValue();

        System.out.println(strokesCounter);
        System.out.println(pointList);
    }
}

class StrokesData {

    List<SessionStrokes> sessionStrokes = new ArrayList<>();

    public List<SessionStrokes> getListOfSessions() {
        return sessionStrokes;
    }
}

class SessionStrokes {

    List<Strokes> strokesList = new ArrayList<>();

    public List<Strokes> getListOfStrokes() {
        return strokesList;
    }

}

class Strokes {

    List<StrokePoint> strokePoints = new ArrayList<>();

    public List<StrokePoint> getListOfStrokePoints() {
        return strokePoints;
    }
}

class StrokePoint {
}