impstuffsforcse
impstuffsforcse

Reputation: 129

List of String lists in Java

I have a list of String lists initialised to object1 as mentioned below:

List<List<String>> object1 = Arrays.asList(Arrays.asList("A", "B", "C"),
                                           Arrays.asList("D", "E", "F"), 
                                           Arrays.asList("G", "H", "I"));

Now I want to create a new list of String lists object let be object 2 as mentioned below:

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

I am not sure whether above written syntax is correct while creating new object "object2" which is same as "object1".

I want to iterate each and every element present in object1 and store in object2 using two for loops (outer and inner loop).

I tried to refer lot of examples but not able to get proper implementation for it.

Upvotes: 0

Views: 1398

Answers (3)

Pshemo
Pshemo

Reputation: 124275

If you don't really need to explicitly use nested loops, instead you can use

  • copy constructor which each list provides,
  • streams and collect its elements with toList() to separate list.

So your code can look like:

List<List<String>> object2 = new ArrayList<>();
for (List<String> row : object1){
    object2.add(new ArrayList<>(row)); //adds separate list containing copy of *row* elements
}

OR with streams:

List<List<String>> object2 = object1.stream()
                                    .map(row -> row.stream().toList())//maps to copy of row
                                    .toList();

Upvotes: 1

Ashish Patil
Ashish Patil

Reputation: 4624

Though you might need to update where you are facing issue, but in meantime this is what my workable attempt is:

        List<List<String>> object1 = Arrays.asList(Arrays.asList("A", "B", "C"), Arrays.asList("D", "E", "F"),
                Arrays.asList("G", "H", "I"));

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

        for (int i = 0; i < object1.size(); i++) {
            List<String> ls = new ArrayList<String>();
            for (int j = 0; j < object1.get(i).size(); j++) {
                ls.add(object1.get(i).get(j));
            }
            object2.add(ls);
        }
    System.out.println(object2);

Output:

[[A, B, C], [D, E, F], [G, H, I]]

Upvotes: 1

Romeo Sheshi
Romeo Sheshi

Reputation: 931

The syntax is correct to iterate each element of object1 and add to object2 just do it this way

        List<List<String>> object1 = Arrays.asList(Arrays.asList("A", "B", "C"),
                Arrays.asList("D", "E", "F"),
                Arrays.asList("G", "H", "I"));
        List<List<String>> object2 = new ArrayList<>();

        for(List<String> list : object1){
            List<String> copyList  =  new ArrayList<>(); 
            for(String value : list){
                copyList.add(value);
            }
            object2.add(copyList);
        }

Upvotes: 1

Related Questions