繁体   English   中英

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

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

我正在尝试使用Google的Guava 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);

    }

}

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

{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摇滚明星花时间帮助一个新人!!

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

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

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

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

请注意,您在此处使用的是ArrayTable ,它是固定大小的,并且要求在创建表时必须提供允许的行键和列键 如果您想添加新的行/列(例如"Oxford" -> "Law" -> value),则应首先使用HashBasedTable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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