How to Use the Guava Table in Java – A Practical Guide
This post will discuss about Guava Table in Java.
You may have encountered situations where you need to store and manipulate data in a two-dimensional structure, such as a spreadsheet or a matrix. For example, you may want to keep track of the grades of students in different courses, or the sales of products in different regions. How would you implement such a data structure in Java?
One option is to use a nested map, such as Map<String, Map<String, Integer>>, where the first key is the row, the second key is the column, and the value is the cell. However, this approach has some drawbacks:
- It is verbose and cumbersome to write and read.
- It requires checking for
nullvalues and creating inner maps when inserting new data. - It does not provide any convenient methods to access or manipulate the data by rows, columns, or cells.
Another option is to use an array or a list of arrays or lists, such as int[][] or List<List<Integer>>, where the indices represent the rows and columns, and the elements are the cells. However, this approach also has some drawbacks:
- It requires knowing the size of the data structure beforehand and resizing it when necessary.
- It does not allow using arbitrary objects as row or column keys, only integers.
- It does not provide any convenient methods to access or change the data by rows, columns, or cells.
Fortunately, there is a better option: using the Guava Table.
1. Overview of Guava Table?
The Guava Table is a collection that represents a table-like structure containing rows, columns, and the associated cell values. The row and the column act as an ordered pair of keys that can be any objects, not just integers. The cell value can also be any object. The Guava Table provides many benefits over the nested map or the array/list approaches:
- It is concise and elegant to write and read.
- It handles
nullvalues and creates inner collections automatically when inserting new data. - It provides many convenient methods to access or manipulate the data by rows, columns, or cells.
- It can handle sparse data, where only a few cells have values, without wasting memory or performance.
- It can support multiple types of row keys and column keys, such as strings, integers, enums, etc.
- It can provide views of the data by rows, columns, or cells, and perform operations such as filtering, transforming, or sorting on them.
- It can create custom table implementations based on different criteria, such as hash-based, tree-based, array-based, or immutable.
The Guava Table is part of the Google Guava library, which is a set of core Java libraries that provide useful utilities and enhancements for common tasks. You can add the Guava dependency to your project using Maven or Gradle.
2. How to Create a Guava Table?
To use Guava Table in your Java project, you need to add the Guava dependency to your build file, such as Maven or Gradle. Then you can create an instance of Guava Table in multiple ways using one of the factory methods from the classes HashBasedTable, TreeBasedTable, ArrayTable, or ImmutableTable. These are discussed below:
1. The create() method from the class HashBasedTable uses LinkedHashMap internally and creates a table that preserves the insertion order of the rows and columns.
|
1 |
Table<String, String, Integer> table = HashBasedTable.create(); |
2. The create() method from the class TreeBasedTable uses TreeMap internally and creates a table that sorts the rows and columns by their natural ordering or by supplying comparators.
|
1 |
Table<String, String, Integer> table = TreeBasedTable.create(); |
3. The create() method from the class ArrayTable uses a two-dimensional array internally and creates a table that has a fixed size and requires knowing the row and column keys beforehand.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import com.google.common.collect.ArrayTable; import com.google.common.collect.Lists; import com.google.common.collect.Table; import java.util.List; class Main { public static void main(String[] args) { List<String> studentRowTable = Lists.newArrayList("David", "Mia", "Michael"); List<String> courseColumnTable = Lists.newArrayList("Math", "Science", "History"); Table<String, String, Integer> table = ArrayTable.create(studentRowTable, courseColumnTable); System.out.println(table); /* { David={Math=null, Science=null, History=null}, Mia={Math=null, Science=null, History=null}, Michael={Math=null, Science=null, History=null} } */ } } |
4. The builder() method from the class ImmutableTable follows a builder pattern and creates an immutable table that does not allow any modifications after creation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; class Main { public static void main(String[] args) { Table<String, String, Integer> table = ImmutableTable.<String, String, Integer>builder() .put("David", "Math", 90) .put("Mia", "Science", 80) .put("Michael", "History", 70) .build(); // {David={Math=90}, Mia={Science=80}, Michael={History=70}} System.out.println(table); } } |
3. How to Use a Guava Table?
Once you have created a Guava Table instance, you can use its methods to store and retrieve data in various ways. Some of the common methods of the Guava Table interface are:
put(R rowKey, C columnKey, V value):Inserts or updates the value for the given row key and column key in the table.get(R rowKey, C columnKey):Returns the value for the given row key and column key in the table, ornullif none exists.remove(R rowKey, C columnKey):Removes the value for the given row key and column key from the table, if any, and returns it.contains(R rowKey, C columnKey):Returns true if the table contains a value for the given row key and column key.rowKeySet():Returns a view of all the row keys.columnKeySet():Returns a view of all the column keys.values():Returns a view of all the cell values.cellSet():Returns a set of all cells in the table, each represented by a Table.Cell object that contains the row key, column key, and value.row(R rowKey):Returns a view of the table as a map from column keys to values for the given row key.column(C columnKey):Returns a view of the table as a map from row keys to values for the given column key.rowMap():Returns a view of the entire table as a nested map from row keys to column keys to values.
Here is a sample code demonstrating the usage of these methods:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import java.util.Collection; import java.util.Map; import java.util.Set; class Main { public static void main(String[] args) { Table<String, String, Integer> table = HashBasedTable.create(); table.put("David", "Math", 90); // David got 90 in Math table.put("Mia", "Science", 80); // Mia got 80 in Science table.put("Michael", "History", 70); // David got 70 in History // {David={Math=90}, Mia={Science=80}, Michael={History=70}} System.out.println(table); int grade = table.get("David", "Math"); // grade = 90 System.out.println(grade); // 90 table.remove("David", "Math"); // David no longer has a grade in Math boolean exists = table.contains("David", "Math"); // exists = false System.out.println(exists); // false Set<String> students = table.rowKeySet(); System.out.println(students); // [Mia, Michael] Set<String> courses = table.columnKeySet(); System.out.println(courses); // [Science, History] Collection<Integer> grades = table.values(); System.out.println(grades); // [80, 70] Set<Table.Cell<String, String, Integer>> cells = table.cellSet(); System.out.println(cells); // [(Mia,Science)=80, (Michael,History)=70] Map<String, Integer> aliceGrades = table.row("Mia"); System.out.println(aliceGrades); // {Science=80} Map<String, Integer> mathGrades = table.column("Science"); System.out.println(mathGrades); // {Mia=80} Map<String, Map<String, Integer>> tableAsMap = table.rowMap(); System.out.println(tableAsMap); // {Mia={Science=80}, Michael={History=70}} } } |
4. Conclusion
The Guava Table is a powerful and convenient collection that allows you to store and manipulate data in a two-dimensional structure. It offers many advantages over the traditional nested map or array/list approaches and provides many methods to access or modify the data by rows, columns, or cells. If you are looking for a simple and elegant way to handle tabular data in Java, you should definitely give the Guava Table a try.
If you want to learn more about Guava Table, you can check out the Guava official website or its GitHub repository.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)