如何检索多维 ArrayTable 中列键的所有值?

How can I retrieve all values for a column key in a multidimensional ArrayTable?

我正在尝试使用 Google 的 Guava tables 包从多维数组 table 中检索所有矩阵值。现在,我可以获得特定列键的所有元素,如下所示:

import java.util.List;
import java.util.Map;

import com.google.common.collect.ArrayTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;

public class createMatrixTable {

    public static void main(String[] args) {

        // Setup table just like a matrix in R
        List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
        List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
        Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);

        // Populate the values of the table directly
        universityCourseSeatTable.put("Mumbai", "Chemical", 120);
        universityCourseSeatTable.put("Mumbai", "IT", 60);
        universityCourseSeatTable.put("Harvard", "Electrical", 60);
        universityCourseSeatTable.put("Harvard", "IT", 120);

        // Get all of the elements of a specific column 
        Map<String, Integer> courseSeatMap = universityCourseSeatTable.column("IT");

        // Print out those elements
        System.out.println(courseSeatMap);

    }

}

控制台中return以下内容:

{Mumbai=60, Harvard=120}

如何在没有行键的情况下仅将值(60 和 120)分配给数组变量?

List<Integer> courseSeatValuesIT = new ArrayList<Integer>();

如果我要打印列表,它将 return 以下内容:

// Print out the variable with just values
System.out.println(courseSeatValuesIT);

[60,120]

感谢所有 Java 摇滚明星花时间帮助新人!!

如果您只需要指定列中的值,只需在返回的地图上使用 .values()

Collection<Integer> courseSeatValuesIT = courseSeatMap.values();
System.out.println(courseSeatValuesIT);

如果需要列表,请复制到新列表:

List<Integer> courseSeatValuesIT = new ArrayList<>(courseSeatMap.values());

请注意,您在这里使用的是 ArrayTable,它是固定大小的,首先需要 allowed row and column keys must be supplied when the table is created. If you ever want to add new row / column (ex. "Oxford" -> "Law" -> value), you should use HashBasedTable