Java how to iterate through an ArrayList of an ArrayList? - java

I am trying to grasp the concept. I have never worked with ArrayLists before (just arrays).
What I have is:
ArrayList<ArrayList<String>> movies = new ArrayList<ArrayList<String>>();
What this will look like or the way I picture it is:
[[Ratatouille, A Bug's Life], [Tangled, Zootopia, Finding Dory], [Harry Potter]]
And say the userInput = 2; then I would subtract 1 from the user input (because Array's and ArrayList's index at 0 that much I know) so userInput= 1; (based on their multiple choice selection, not very important).
Then what I want to do is take the index 1 so [Tangled, Zooptopia, Finding Dory] and loop through that index and add it to an ArrayList (not ArrayList of an ArrayList).

No need to loop - You can access an ArrayList by an index, and then use the addAll method to add all the elements of the ArrayList in that position to your result:
result.addAll(movies.get(userInput - 1));

following with following code you can iterate through an arrayList
private ArrayList<String> myArrayList = new ArrayList<>();
for(int i=0;i<myArrayList.size();i++){
myArrayList.get(i);
// Perform whatever operation here
}
Let me know if it doesn't work. And also what's the error given

The ArrayList.get(int index) method can help you out.
ArrayList myList = fullList.get(1);
would give you your desired list and you can iterate over it like:
for (String currString: myList){
//Do things with currString
}
I hope I explained it well :)

You should learn how to use Java Lambdas. you can use a lambda to iterate through an ArrayList since ArrayLists are Iterable.
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {System.out.println(arrayList.get(1));});
or
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {\*code here!*\});
if you're trying nest iterations you can:
ArrayList<ArrayList<String>>arrayListofarrayList = new ArrayList<ArrayList<String>>();
arrayListofarrayList.forEach((arrayList) -> {
arrayList.forEach((item) -> {
System.out.println(item);
});
});

Declare your variable as following
private ArrayList<String> arrayList = new ArrayList<>();
Then in a method add following
for(int j=0; j < arrayList.size() ; j++){
arrayList.get(i);
// Your code goes here
}
This should work

You can use either for-each loop or simple for loop to print elements in ArrayList of ArrayList. For example,
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(3);list2.add(4);
ArrayList<Integer> list3 = new ArrayList<>();
list3.add(5);list3.add(6);
ArrayList<ArrayList<Integer>> listOfList = new ArrayList<>();
listOfList.add(list1);
listOfList.add(list2);
listOfList.add(list3);
// Printing elements using for-each loop
for(ArrayList<Integer> eachList : listOfList){
for(Integer elementInList : eachList){
System.out.print(elementInList + "\t");
}
System.out.println();
}
// Printing elements using for loop
for(int i = 0;i < listOfList.size();i++){
ArrayList<Integer> eachList = listOfList.get(i);
for(int j = 0;j < eachList.size();j++){
System.out.print(eachList.get(j) + "\t");
}
System.out.println();
}
Output:

Related

Java 2D arraylists

I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.

How to initialize inner ArrayList of a two-dimensional ArrayList

The below ArrayList is a two-dimensional ArrayList of size parts. I'm divding the storeIds into parts of ArrayList and add them to the inner ArrayList of the 2D ArrayList.
ArrayList<ArrayList<String>> partStoreIds = new ArrayList<ArrayList<String>>(parts);
for(int i = 0; i < parts; i++)
{
System.out.println("Executing part: " + i);
int maxIndex = Math.min(storeIds.size(), querySize*(i+1));
//The below line is throwing an exception
partStoreIds.addAll(storeIds.subList(querySize*i, maxIndex));
}
What you try to achieve can be done as next:
partStoreIds.add(new ArrayList<>(storeIds.subList(querySize*i, maxIndex)));
Indeed, as partStoreIds is an ArrayList of ArrayList only ArrayList instances can be added and since storeIds.subList(querySize*i, maxIndex) returns a List, you need to convert it first as an ArrayList using the constructor new ArrayList(Collection).
But a much simpler approach would be to declare your partStoreIds as a List of List, then you can add your subList directly as next:
List<List<String>> partStoreIds = new ArrayList<>(parts);
...
partStoreIds.add(storeIds.subList(querySize*i, maxIndex));
You need to create a new ArraraList and then add items to it
ArrayList<String> temp=new ArrayList<String>();
temp.addAll(storeIds.subList(querySize*i, maxIndex));
partStoreIds.add(temp);

java 2d arraylist edit inside loop

I have a 2d ArrayList which stores objects, i want to check if a certain object exists in any of of the rows, and if not add a new row, and search that object in future checks. eg.
ArrayList<List<Object>> list = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
list.add(newList);
}
}
This gives me a 'ConcurrentModificationException' but I can't find another way to do it.
Thanks in advance.
list.add(newList); this line should be outside your for loop. You are trying to modify your list while iterating on it. Just keep adding elements to newList in the for loop. Add the line list.add(newList); after the for loop.
You cannot change a List while you are iterating over its items.
What you can do is:
ArrayList<List<Object>> list = new ArrayList<>(); // in practice this would not be an empty list, but it would, as in your example, contain all items
ArrayList<List<Object>> newRows = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
newRows.add(newList);
}
}
list.addAll(newRows);
You have to replace:
for(List o : list) {
with:
for(int i = 0; i < list.size(); i++) {
List o = list.get(i);
Just be careful when you do this to handle how you modify the list. In this case there should be no problem.

why assign ArrayList to new ArrayList temp

I am looking at the code for Permutations problem on leetcode. For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
And I found there is one sentence
ArrayList<Integer> temp = new ArrayList<Integer>(l);
I have no idea why here needs to assign the "l" to "temp". And I tried current.add(l) direclty but gave me the wrong answer. Can you help me with this?
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
//System.out.println(temp);
// - remove num[i] add
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
}
I have no idea why here needs to assign the "l" to "temp"
He's not - that would just be:
ArrayList<Integer> temp = l;
Instead, the code creates a copy of the content of the list l refers to, in a new ArrayList. That means that future changes to the list that l refers to (such as the call to l.remove(j) immediately afterwards) don't affect the new list.
As a simple stand-alone example of that, consider:
List<String> original = new ArrayList<>();
original.add("foo");
List<String> copy = new ArrayList<>(original);
System.out.println(copy.size()); // 1
original.add("bar");
System.out.println(copy.size()); // Still 1
Admittedly the code is written in a very odd manner - until the final statement, result only ever has a single element, so iterating over it is pretty pointless - but I believe that explains the single statement you were asking about.
If you did
current.add(l);
you would be adding the same reference to the ArrayList l to current. So, if you made some changes in one of those lists, both would be modified. In order to avoid that issue, in the line
ArrayList<Integer> temp = new ArrayList<Integer>(l);
you are creating a different ArrayList but with the same content. So, they will be different objects (different references).

Adding element in two dimensional ArrayList

I know that for arrays you can add an element in a two dimensional array this way:
array[0][1] = 17; //just an example
How can I do the same thing with ArrayList?
myList.get(0).set(1, 17);
maybe?
This assumes a nested ArrayList, i.e.
ArrayList<ArrayList<Integer>> myList;
And to pick on your choice of words: This assigns a value to a specific place in the inner list, it doesn't add one. But so does your code example, as arrays are of a fixed size, so you have to create them in the right size and then assign values to the individual element slots.
If you actually want to add an element, then of course it's .add(17), but that's not what your code did, so I went with the code above.
outerList.get(0).set(1, 17);
with outerList being a List<List<Integer>>.
Remember that 2-dimensional arrays don't exist. They're in fact arrays or arrays.
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
data.get(0).add("String");
ArrayList<ArrayList<String>> contains elements of type ArrayList<String>
Each element must be initialised
These elements contain elements of type String
To get back the String "String" in the 3-line example, you would use
String getValue = data.get(0).get(0);
the way i found best and convinient for me was to declare ur 2d arrayList and then also a nornal mono-dimension array.
ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
ArrayList<String> 1darraylist=new ArrayList<>();
then fill the '1D'array list and later add the 1D to the 2D array list.
1darraylist.add("string data");
2darraylist.add(idarraylist);
this will work as long as your problem is simply to add to elements to the list. if u want to add them to specific positions in the list, the the .get().set(); is what u wanna stick to.
ArrayList<ArrayList<Integer>> FLCP = new ArrayList<ArrayList<Integer>>();
FLCP.add(new ArrayList<Integer>());
FLCP.get(0).add(new Integer(0));
Each element must be instantiated. Here the outer ArrayList has ArrayList element, and first you need to add an element to reference it using get method.
Some additional notes; after reading other answers and comments:
1> Each element must be instantiated; initialization is different from instantiation (refer to flexJavaMysql's answer)
2> In Java, 2-dimensional arrays do exist; C# doesn't have 2D arrays (refer to JB Nizet's answer)
String[] myList = {"a","b","c","d"};
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
int outerIndex =0;
int innerIndex =0;
for (int i =0; i<list.length; i++) {
data.get(outerIndex).add(innerIndex, list[i]);
innerIndex++;
}
System.out.println(data);
Simple for loop to add data to a multidimensional Array.
For every outer index you need to add
data.add(new ArrayList<String>());
then increment the outer index, and reset the inner index.
That would look something like this.
public static String[] myList = {"a", "b","-","c","d","-","e","f","-"};
public static ArrayList<ArrayList<String>> splitList(String[] list) {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
int outerIndex =0;
int innerIndex =0;
for (int i=0; i<list.length; i++) {
System.out.println("will add: " + list[i]);
if(!list[i].contains("-")) {
System.out.println("outerIndex: " + outerIndex +" innerIndex: "+ innerIndex);
data.get(outerIndex).add(innerIndex, list[i]);
innerIndex++;
} else {
outerIndex++; // will move to next outerIndex
innerIndex = 0; // reset or you will be out of bounds
if (i != list.length-1) {
data.add(new ArrayList<String>()); // create an new outer index until your list is empty
}
}
}
return data;
}
public static void main(String[] args) {
System.out.println(splitList(myList));
}

Categories

Resources