Home > database >  How do I add an array into an arraylist (so that it becomes a 2D arraylist) in java?
How do I add an array into an arraylist (so that it becomes a 2D arraylist) in java?

Time:03-20

I have an array:

String[] a = {"abc","def","ghi"}

Now I want to store this array into my string arraylist

ArrayList<String> arr = new ArrayList<>();

so that it becomes like this:

[["abc","def","ghi"]]

I have tried this code but it doesn't work:

arr.add(Arrays.asList(a));

Please help me

CodePudding user response:

Since Arrays.asList(a) returns List, to add it to your list you need to use addAll()

arr.addAll(Arrays.asList(a));

Instead of

arr.add(Arrays.asList(a));

But the result will be ["abc","def","ghi"]

If you want to achieve this [["abc","def","ghi"]] then define your ArrayList as

List<List<String>> arr = new ArrayList<>();

CodePudding user response:

using arralist addAll() method we can do but, Using arrayList is depricated approach , use Streams instead of it:

System.out.println(Collections.singletonList(Stream.of(new String[] {"abc","def","ghi"}).collect(Collectors.toList())));

will result in:

[[abc, def, ghi]]

  •  Tags:  
  • java
  • Related