Home > database >  2D arraylist with one element into 1D arraylist in java
2D arraylist with one element into 1D arraylist in java

Time:11-22

If I know that my ArrayList<ArrayList<String>> will only contain one element (one list inside a list) how can I transform it into a 1D ArrayList. Such that from [["A","B"]] I get ["A","B"]?

CodePudding user response:

If we run under Java 8 , we will be able to use the java.stream API to solve the problem:

listOfLists.stream() // transform the list into a stream, i.e. each element in 
                     // the list (in our case: List<String>) will appear in the 
                     // Stream.

    .flatMap(List::stream) // flatten the stream: for each element in the stream 
                           // (List<String> in our case), stream those entries 
                           // (Strings), construct a new stream over all entries 
                           // (Strings) of all List<String>s in the stream

    .collect(Collectors.toList()); // returns all `String`s in a new List<String>

Ideone demo

CodePudding user response:

I think you just need to get the first element with the get method. Then you put it in a new variable that you call oneD for example.

  • Related