I have the following ArrayList...
ArrayList<ArrayList<Integer>> row1 = new ArrayList<ArrayList<Integer>>();
The following arraylists are added to it....
row1.add(cell1);
row1.add(cell2);
row1.add(cell3);
row1.add(cell4);
row1.add(totalStockCell);
I want to iterate through the arraylist row1 and print the contents.
Would a loop within a loop work here?
E.g.
while(it.hasNext()) {
//loop on entire list of arraylists
while(it2.hasNext) {
//each cell print values in list
} }
This is the canonical way you do it:
for(List<Integer> innerList : row1) {
for(Integer number : innerList) {
System.out.println(number);
}
}
for (ArrayList<Integer> list : row1)
{
for (Integer num : list)
{
//doSomething
}
}
Java enhanced-for loops use an iterator behind the scenes.
If you want to use Iterator, nested loops will work:
Iterator<ArrayList<Integer>> it = row1.iterator();
while(it1.hasNext())
{
Iterator<Integer> itr = it.next().iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
Here some functional approach:
ArrayList<ArrayList<Integer>> row1 = new ArrayList<>();
row1.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
row1.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
row1.stream().flatMap(Collection::stream).forEach(System.out::println);
Old question, but I am just curious why no one has mentioned this way,
for(int i=0; i<list.size(); i++) {
for(int j=0; j<list.get(i).size(); j++) {
System.out.print(list.get(i).get(j) + " ");
}
System.out.println();
}
This is same as accessing a matrix in 2D arrays.
Related
what is the correct way to iterate through an array list without getting an exception thrown? I tried this:
while(packages.get(i)!=null)
{
if(packages.get(i).equals(z))
{
packages.remove(i);
this.setNumPack(this.getNumPack()-1);
}
i++;
}
It throws exception when the index is bigger than the size of the array list.I also tried to iterate as long as the iterator was smaller than the size of the array but it didnt help. Thanks
There are many ways to iterate and remove, but in your specific code the solution is not to increment the index if you remove an element (since removing an element decrements the indices of all the elements that come after the removed element) :
while(packages.get(i)!=null)
{
if(packages.get(i).equals(z))
{
packages.remove(i);
this.setNumPack(this.getNumPack()-1);
} else {
i++;
}
}
Of course packages.get(i) would still throw an exception when i reaches packages.size(), so a for loop would be better:
for (int i = 0; i < packages.size(); i++)
{
if(packages.get(i).equals(z))
{
packages.remove(i);
this.setNumPack(this.getNumPack()-1);
i--;
}
}
for (int i = 0; i < packages.size(); i++) {
if(packages.get(i).equals(z)) {
packages.remove(i);
this.setNumPack(this.getNumPack()-1);
}
}
usual way :
for (int i = 0; i < list.size(); i++)
'new' way :
for ('your type' item : list)
You can check if the list is null or if the list has null elements... those are 2 compl. different things
an iterator can be implemeted, but you need to explicitly check null values...
List<Integer> l = Arrays.asList(1, null, 3, 4, 5, null);
Iterator<Integer> it = l.iterator();
while (it.hasNext()) {
Integer integer = (Integer) it.next();
if (integer != null) {
System.out.println("the element is holding: " + integer);
} else {
System.out.println("the element is null");
}
}
or a classical enhanced loop
List<Integer> l = Arrays.asList(1, 2, 3, 4, 5, null);
if (l != null) {
for (Integer integer : l) {
if (integer != null) {
System.out.println("the element is holding: " + integer);
} else {
System.out.println("the element is null");
}
}
} else {
System.out.println("the list is null");
}
You can use any one of them
//Loop Arraylist using foreach loop of JDK1.5
System.out.println("ArrayList Loop Example using foreach loop of JDK 1.5");
for(String element: loopList){
System.out.println(element);
}
//Loop Arraylist using simple for loop and size method
System.out.println("ArrayList Loop Example using for loop and size()");
for(int i=0; i<loopList.size(); i++){
System.out.println(loopList.get(i));
}
//Iterate Arraylist using iterator and while loop in Java
System.out.println("ArrayList Loop Example using Iterator and while loop");
Iterator<String> iterator = loopList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//Iterate Arraylist using ListIterator and while loop in Java
System.out.println("ArrayList Loop Example using ListIterator and while loop");
ListIterator<String> listIterator = loopList.listIterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
You also can use Java 8 stream API
List<Integer> list = Arrays.asList(1, 3, 4, 5);
list.stream().forEach(System.out::println);
You will run into problems sooner or later by iterating from head to tail in an arraylist if you plan to remove elements along the way. The trick is to iterate from tail to head since all of the reordering being done in the list is done from the removed index to the end of the list, - not on indexes before the one removed.
pseudo-code:
for(int i = list.size()-1; i >=0; i--){
list.remove(i);
}
I seem to be having trouble in the logic of my problem. What I am trying to do is have a List of Arrays. Each Array contains 2 String.
I am trying to iterate through my List and then printing the elements of the arrays. I seem to get stuck in printing the first Array (which is what my code does), though I am stuck in the logic.
public static void main(String[] args) {
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress1 = new ArrayList<String>();
singleAddress1.add("17 Fake Street");
singleAddress1.add("18 Fake Street");
ArrayList<String> singleAddress2 = new ArrayList<String>();
singleAddress2.add("Phoney town");
singleAddress2.add("not real town");
ArrayList<String> singleAddress3 = new ArrayList<String>();
singleAddress3.add("sillyname town");
singleAddress3.add("alsosilly town");
addresses.add(singleAddress1);
addresses.add(singleAddress2);
addresses.add(singleAddress3);
System.out.print("Original contents of al: " + addresses + "\n");
Iterator itr = addresses.iterator();
while (itr.hasNext()) {
Object element = itr.next();
System.out.print(element + "\n");
for (int i = 0; i < singleAddress1.size(); i++) {
System.out.println(singleAddress1.get(i));
}
itr.remove();
}
}
}
Whilst you are iterating over the outer array list addresses, internally you end up iterating on same singleAddress1 instead of all the list elements which you would get from iterator using for (int i = 0; i < singleAddress1.size(); i++) {.
Your iteration loop should be:
Iterator<List<String>> itr = addresses.iterator();
while (itr.hasNext()) {
List<String> element = itr.next();
^^^^^^^^^^^^
System.out.print(element + "\n");
for (int i = 0; i < element.size(); i++) {
^^^^^^^^
System.out.println(element.get(i));
}
itr.remove();
}
Why don't you use a simple for-each loop:
for(List<String> list:addresses)
{
for(String str:list)
{
System.out.println(str);
}
}
I have an arraylist in which
ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();
in the list of items I have items like this
[[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22]]
how to iterate and store in another array these values split into two like
[1,2,3,4,5,6,7,8,9,10,11] and [11,12,13,14,15,16,17,18,19,20,21,22]. I have used advanced for loop
for(ArrayList<String> list:listofItems)
{
for (String s:list)
{
//I dont know how to add logic here.
}
}
I am assuming here that both lists will also hold string type data.If you want Integer type,you can parse while adding.
ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
for (ArrayList<String> list : listofItems) {
for (String s : list) {
// there shud be some condition how much elements you want in a
// list or some condition
// to decide in which list we need to add item
if (list.size() < 12)
list1.add(s);
else
list2.add(s);
}
}
Use something like that:
if (yourlist.size()>0) {
List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}
Would be separate your list in 2 lists divided in the half.
You can use this code to store your list into another list.
List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
for (String s:list) {
stringList.add(s);
}
}
In this case, when you add info to listOfItems, you should try example like this
for(int i = 0; i< 2; i++){
for(int j = 0; j < n; j++){
/// add util break n
lists.get(i).add(strTemp);
}
}
You can change i < 2 into any number you want. I only make this sample for you.
My Code is as follows:
ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);
I want the following pattern during printing:
[1,2,4]
I tried both for loop and Iterator but I am not getting the desired output.
Help me to sort out!
I found the solution and that is
for(int i=0;i<al.size();i++) {
if(al.get(i)!=3)
System.out.println(al.get(i));
}
thanks for your help
Now I want to get the same output, not through printing but by deleting elements of ArrayList, I tried with the same condition but I got exception
and the answer is
Iterator<Integer> iter = al.iterator();
while (iter.hasNext()) {
if (iter.next().intValue() == 3) {
iter.remove();
}
}
System.out.println(al);
Step through all the items in the ArrayList and test if they are equal to 3, if they are not, print them.
for (Integer i : al) //for each Integer in the al list
{
if (!i.equals(3)) //if it is NOT (!) equal to 3
{
System.out.println(i); //then print it
}
}
Obviously if you want to skip more than just the number 3 you will need to expand the condition the if uses.
Note on removing elements from the list
If you try and remove from the list within the loop using this method you will encounter problems with ConcurrentAccessException, this is dealt with in this question.
If you want to get the list element and as per your output it seems you want to print 1 and even numbers in the list
for(int i=0; i< a1.size(); i++) //iterate over List
{
if(a1.get(i)%2=0 || a1.get(i) == 1) //print if 1 or even
System.out.println(a1.get(i));
}
You can also use the forEach method (Java 8):
al.forEach(v -> {if(v!=3) System.out.println(v);});
add the required skipping values in a list and check against that list before printing
My code:run and give comment(views please)
import java.util.*;
public class Mycode{
public static void main(String []args){
ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);
ArrayList<Integer> al1 = new ArrayList();
al1.add(3);
al1.add(2);
int flag=0;
for(int j=0; j< al.size(); j++)
{
flag=0;
for(int i=0; i< al1.size(); i++)
{
if(al.get(j)==al1.get(i))
flag=1;
}
if(flag==0)
System.out.println(al.get(j));
}
}
}
I do have this code, and I would like to print out all the array's values of Arraylist.
thanks for your help in advanced.
here is my code:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
For printing elements of an array stored in arraylist,you will have to to do the following:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
Edit your code with further detail on your data structure
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
See if this can work for you. I think it's simpler:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
Below code works fine for me
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}