Search code examples
javaguava

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


I'm trying to retrieve all matrix values from a multidimensional array table, using Google's Guava tables package. Right now, I can get all elements for a specific column key as follows:

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

    }

}

Which returns the following in the console:

{Mumbai=60, Harvard=120}

How can I assign just the values (60 and 120) to an array variable without the row keys?

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

Such that if I were to print the list, it would return the following:

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

[60,120]

Thanks to any Java rock stars who take the time to help out a new guy!!


Solution

  • If you want only values from specified column, just use .values() on returned map:

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

    If you need list, copy it to new one:

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

    Note that you're using ArrayTable here, which is fixed-size and requires 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 in first place.