Question

I trying to write some code in Java - I have two Lists:

List<List<Integer>> listOfLists;
List<Integer> listOfIntegers;

I want to add each of the Integers in listOfIntegers to a new element (List) in listOfLists, then I need to clear listOfIntegers

I tried:

listOfLists.add(listOfIntegers);
listOfIntegers.clear();

but this clears the reference to the List in listOfLists

Thanks to Manuel Silva I came up with what I need:

List<Integer> newList = new ArrayList<>();
for (Integer i : lineIntegersList)
{
    newList.add(i);
}

listOfLists.add(newList);                   
lineIntegersList.clear();
Was it helpful?

Solution

You could do something like this...

 ArrayList<ArrayList<String>> listOlists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOlists.add(singleList);

ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOlists.add(anotherList);

thanks @tster - here you instantiate your "parent list" and as you would know how to do - just create a child list to add to the parent.. :D

OTHER TIPS

for (Integer i: listOfIntegers) {
 List<Integer> list = new LinkedList<Integer>();
 list.add(i);
 listOfLists.add(list);
}

This solution basically adds a new List with one element for each integer in the list of integer to the initial list of list

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top