user6389648 - 1 year ago 75
Java Question

# Correct and Efficient Way to read the Elements Column Wise

I am unable to find the correct way of reading the elements column wise.

Input is a List which contains 10 list and these 10 list contains elements having variable Column Size

What I did

Task2: Finding the maximum size a column can have so that I can apply the loop till that Column.

Retrieving the List ColumnWise.

Code:

``````    List<List<Integer>> outer=new ArrayList<>();
ArrayList<Integer> innerSize=new ArrayList<Integer>();
List<Integer> inner=null;
int ar[][]=new int[10][];
int ar1[] =new int[ar.length];
for(int i=0;i<10;i++)
{
System.out.println("Enter the Size of the list "+i);
String s1=sc.next();

int N=Integer.parseInt(s1); //Calculate the Size:
inner=new ArrayList<Integer>();
for(int j=0;j<N;j++)
{
System.out.println("Enter the Elements of the list "+i);

}
System.out.println(inner);
}
System.out.println(outer);

System.out.println("Finding the maximum element");
Integer max=null;
Iterator<Integer> ltr=innerSize.listIterator();
if(ltr.hasNext())
{
Integer element=(Integer)ltr.next();
max=element;
while(ltr.hasNext())
{
Integer element1=(Integer)ltr.next();
if(element1>max)
{
max=element1;
}
}
}
System.out.println("Maximum Element is"+max);

//Retrieving the List ColumnWise.
Iterator ltr1=outer.listIterator();

for(int j=0;j<max;j++)
{

while(ltr1.hasNext())
{
List l0tol9=(List)ltr1.next(); //I have one list taken from the 10 lists.
Iterator ltr2=l0tol9.listIterator();
while(ltr2.hasNext())
{
Integer i1=(Integer)ltr2.next();
if(i1!=null)
{
System.out.println(i1);
break;
}
}
}

}
``````

Input:Lets say I got this list from user:(outerList with max Column Size 2)

``````[[1], [1], [1, 2], [1], [1], [1], [1], [1], [1], [1]] //outerlist
``````

Expected Output
is

``````1
1
1
1
1
1
1
1
1
1
2
``````

Output Shown:(Only 1st Column)

``````1
1
1
1
1
1
1
1
1
1
``````

Here is an easy way to browse 2-D Lists column-wise :

``````int maxColSize = outer.stream().mapToInt(List::size).max().orElse(0);
for (int y=0; y<maxColSize; y++) {
for (int x=0; x<outer.size(); x++) {
List<Integer> currentInner = outer.get(x);
if (currentInner.size() > y) {
System.out.println(currentInner.get(y));
}
}
}
``````

You can try it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download