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

时间:2017-12-04 14:04:24

标签: java guava

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

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);

    }

}

在控制台中返回以下内容:

{Mumbai=60, Harvard=120}

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

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

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

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

[60,120]

感谢任何花时间帮助新人的Java摇滚明星!

1 个答案:

答案 0 :(得分:1)

如果您只想要指定列中的值,请在返回的地图上使用.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。如果您想要添加新的行/列(例如"Oxford" - &gt; "Law" - &gt;值),则应首先使用HashBasedTable