简体   繁体   中英

Programmatically create 2D ArrayList and then create a single ArrayList from it

Programmatically create 2D ArrayList in java and then create a single ArrayList from it.

I have an ArrayList<Integer> IntegerArraylist of 5 Integers like this {1,2,3,4,5};

Based on this I have to create 2D ArrayList like:

ArrayList<ArrayList<String>> StringArraylist;

Like this:

{{a}, {b, c, d, e, f}, {g, h}, {i, j, k}, {l}}

Now based on this I have to convert it to single ArrayList like this:

{a, b, c, d, e, f, g, h, i, j, k, l}

How can we do this?

List<String> list = new ArrayList<String>();
    for (String[] array : YOUR_2D_ARRAY) {
        list.addAll(Arrays.asList(array));

I think the easiest way to do this is using StreamAPI

public static void main(String[] args) {
   String[][] arr = {
       {"a"},
       {"b", "c", "d", "e", "f"},
       {"g", "h"}
       // and so on
   };

   List<List<String>> stringArraylist = Arrays.stream(arr)
       .map(Arrays::asList)
       .collect(Collectors.toList());
    
   List<String> merged = stringArraylist.stream()
       .flatMap(List::stream)
       .collect(Collectors.toList());

   System.out.println(merged);
}

Or, simple use for-each loop:

List<String> merged = new ArrayList<>();
for(List<String> list : stringArraylist) {
    merged.addAll(list);
}

Note that you need to use the List interface and not the ArrayList implementation.

You can use streams with flatMap

 Stream<String> oneDStream = StringArraylist.stream().flatMap((Function<ArrayList<String>, Stream<String>>) strings -> strings.stream());
 List<String> oneDList = oneDStream.collect(Collectors.toList());
 oneDList.forEach(s -> {
     System.out.print(" "+ s);
 });

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