I have a following ArrayList,
[Title,Data1,Data2,Data3]
[A,2,3,4]
[B,3,5,7]
And I would like to convert this one like this,
Check whether all lists have the same size.
Place the informations in a Matrix (List with List elements, for example) to get the number of lists and size of a list.
Create a new Matrix with the rotated size informations. (3x4 to 4x3)
Implement 2 For loops and place the elements into the new matrix.
Do you have a fixed number of ArrayLists and are they of fixed size to begin with? If it is fixed, what you can do is have an int index value and process each ArrayList in turn in the same loop. You can then transfer each value to a temporary ArrayList and then place a reference to this in a final ArrayList for output.
Sounds confusing? Here's a rough solution:
ArrayList tempList = new ArrayList();
ArrayList outputList = new ArrayList();
for(index=0;index<list1.getsize();index++){
// Add null checks and other validation here
tempList.add( list1.get(index) );
tempList.add( list2.get(index) );
tempList.add( list3.get(index) );
outputList.add( tempList );
}
Since get(index)
could harm your performance dramatically i.e. for big linked list I would recommend using @polygenelubricants solution but with an iterator approach.
public static <T> List<List<T>> transpose(List<List<T>> table) {
List<List<T>> ret = new ArrayList<List<T>>();
final int N = table.stream().mapToInt(l -> l.size()).max().orElse(-1);
Iterator[] iters = new Iterator[table.size()];
int i=0;
for (List<T> col : table) {
iters[i++] = col.iterator();
}
for (i = 0; i < N; i++) {
List<T> col = new ArrayList<T>(iters.length);
for (Iterator it : iters) {
col.add(it.hasNext() ? (T) it.next() : null);
}
ret.add(col);
}
return ret;
}
This is called transposition. The following snippet does what you need:
import java.util.*;
public class ListTranspose {
public static void main(String[] args) {
Object[][] data = {
{ "Title", "Data1", "Data2", "Data3" },
{ "A", 2, 3, 4 },
{ "B", 3, 5, 7 },
};
List<List<Object>> table = new ArrayList<List<Object>>();
for (Object[] row : data) {
table.add(Arrays.asList(row));
}
System.out.println(table); // [[Title, Data1, Data2, Data3],
// [A, 2, 3, 4],
// [B, 3, 5, 7]]"
table = transpose(table);
System.out.println(table); // [[Title, A, B],
// [Data1, 2, 3],
// [Data2, 3, 5],
// [Data3, 4, 7]]
}
static <T> List<List<T>> transpose(List<List<T>> table) {
List<List<T>> ret = new ArrayList<List<T>>();
final int N = table.get(0).size();
for (int i = 0; i < N; i++) {
List<T> col = new ArrayList<T>();
for (List<T> row : table) {
col.add(row.get(i));
}
ret.add(col);
}
return ret;
}
}