Java threads: collecting a nested collection

I am learning how to use Java streams, and you need some help to figure out how to pass nested collections and collect the results back to the collection.

In the simple example below, I created 2 ArrayLists and added them to the ArrayList. I want to be able to perform a simple function for each nested collection, and then write the results to a new collection. The last line of code does not even compile. Any explanation 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()); 
+5
source share
2 answers

The problem is that List#add does not return List . Instead, you need to return the list after displaying:

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

Or you can skip using map and do it using forEach , since the ArrayList changed:

 nested.forEach(list -> list.add(100)); 
+1
source

You can use Stream.of() to do this without creating a pre-nested stricture.

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

And maybe pull the card operation into a separate function.

0
source

Source: https://habr.com/ru/post/1273118/


All Articles