简体   繁体   中英

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  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM