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,
The mathematics behind: you need to transpose the matrix. It's easier if you use a 2-dimensional array or a 'List of Lists', which is pretty much he same with collections. A List of arrays works too, but it is slightly more confusing.
This wikipedia article shows some algorithms for transposition.
The technique is called transposing. Example of an implementation.
public static MyObject [][] transpose(MyObject [][] m){
int r = m.length;
int c = m[r].length;
MyObject [][] t = new MyObject[c][r];
for(int i = 0; i < r; ++i){
for(int j = 0; j < c; ++j){
t[j][i] = m[i][j];
}
}
return t;
}
Here is my solution.Thanks to @jpaugh's code.I hope this will help you.^_^
public static <T> List<List<T>> transpose(List<List<T>> list) {
final int N = list.stream().mapToInt(l -> l.size()).max().orElse(-1);
List<Iterator<T>> iterList = list.stream().map(it->it.iterator()).collect(Collectors.toList());
return IntStream.range(0, N)
.mapToObj(n -> iterList.stream()
.filter(it -> it.hasNext())
.map(m -> m.next())
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
This called a transpose operation. A code sample is here, , but will need significant modification as you have an ArrayList of Arrays (what I infer from your question)
something like this maybe
List<List<String>> list = new ArrayList<List<String>>(firstList.size());
for(int i = 0; i < firstList.size(); i++) {
list.add(Arrays.asList(
firstList.get(i),
secondList.get(i),
thirdList.get(i))
);
}
If it is for a datamigration task, you might consider your friendly spreadsheet if the size is not too big.
For matrix manipulation stuff there is the jScience library which has matrix support. For just transposing a metrix this would be overkill, but it depends what needs to be done with it.