简体   繁体   中英

Java streams: Collect a nested collection

I'm learning how to use Java streams and need some help understanding how to stream nested collections and collect the results back into a collection.

In the simple example below, I've created 2 ArrayLists and added them to an ArrayList. I want to be able to perform a simple function on each nested collection and then capture the results into a new collection. The last line of code doesn't even compile. Any explanations would be appreciated!

    ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1,2,3));
    ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(4,5,6));

    ArrayList<ArrayList<Integer>> nested = new ArrayList<ArrayList<Integer>>();
    nested.add(list1);
    nested.add(list2);

    ArrayList<ArrayList<Integer>> result = nested.stream()
            .map(list -> list.add(100))
            .collect(Collectors.toList());

The problem is that List#add doesn't return a List . Instead, you need to return the list after the mapping:

List<ArrayList<Integer>> result = nested.stream()
        .map(list -> {
            list.add(100);
            return list;
        })
        .collect(Collectors.toList());

Or you may skip using map and do it using forEach , since ArrayList is mutable:

nested.forEach(list -> list.add(100));

You can use Stream.of() to do this, without creating the nested stricture beforehand.

        List<ArrayList<Integer>> nestedList = Stream.of(list1, list2)
            .map(list -> {list.add(100); return list;})
            .collect(Collectors.toList());

And maybe extract the map operation into a separate function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM