java flatten list

https:/‮l.www/‬autturi.com
java flatten list

To flatten a list in Java, you can use the stream() method to create a stream of the list, and then use the flatMap() method to flatten the stream into a single stream of elements.

Here's an example of how to do it:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    List<List<Integer>> list = Arrays.asList(
      Arrays.asList(1, 2, 3),
      Arrays.asList(4, 5, 6),
      Arrays.asList(7, 8, 9)
    );

    // Flatten the list
    List<Integer> flatList = list.stream()
      .flatMap(l -> l.stream())
      .collect(Collectors.toList());

    System.out.println(flatList);  // prints "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
  }
}

This code creates a list of lists and then uses the flatMap() method to flatten the inner lists into a single stream of elements. The collect() method is then used to collect the elements into a new list.

You can use a similar approach to flatten any type of list, as long as you use the appropriate stream and collect methods.

Note that this approach only works if the list is nested to a single level. If the list is nested to multiple levels, you may need to use the flatMap() method multiple times to flatten the list completely.

Created Time:2017-11-03 15:57:14  Author:lautturi