开发者

Translate collection of collections in Java

let say we have a collection of collections which results in a table data structure.

Collection<Collection<T>> table;

Which is most efficient way you would use to translate the "rows" into "columns" using Java?

EDIT:

val_11  val_12  val_13  val_14
val_21  val_22  开发者_Go百科val_23  val_24
val_31  val_32  val_33  val_34

should be translated to

val_11  val_21  val_31
val_12  val_22  val_32
val_13  val_23  val_33
val_14  val_24  val_34


Transpose method that assumes that the collection of collections represents a matrix:

public List<List<T>> transpose(Collection<Collection<T>> table) {
    boolean init = false;

    List<List<T>> result = new ArrayList<List<T>>();
    for (Collection<T> row: table) {
        if (!init) {
            for(int i = 0; i < row.size(); i++)
                result.add(new ArrayList<T>(table.size());
            init = true;
        }

        for(int i = 0; i < row.size(); i++)
            result.get(i).add(row.get(i));
    }

    return result;
}


If you were to use a Guava Table rather than a Collection<Collection<T>>, you'd be able to use Tables.transpose to create a view of the table with row keys and column keys switched. Of course, you'd need to deal with keys for your rows and columns (integers probably) rather than just not having row or column keys at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜