Java – get all keys by the value of a table column
I have a tabular data representation in Java
In view of this table
|----------------------------------------------| | Artist | Genre | Type | |----------------------------------------------| | Eddie Van Halen | Musician | Hard Rock | | David Bowie | Musician | Art Pop | | David Lynch | Director | Surrealist Film | | George Lucas | Director | Blockbuster | |----------------------------------------------|
I use this
Table<String,String,String> table = HashBasedTable.create(); table.put("Eddie Van Halen","Genre","Musician"); table.put("Eddie Van Halen","Type","Hard Rock"); table.put("David Bowie","Musician"); table.put("David Bowie","Art Pop"); table.put("David Lynch","Director"); table.put("David Lynch","Surrealist Film"); table.put("George Lucas","Director"); table.put("George Lucas","Blockbuster");
Create a table object
It is easy to get data using row or column keys So I might get the type of David Bowie:
table.get("David Bowie","Genre"); // "Musician"
I can also get all the data for a specific column:
table.column("Genre").values(); // [Musician,Director,Musician,Director]
My main interest is to find all the artists. They are all directors In this case, it looks up by value There are two-dimensional maps, such as the bidimap of Apache collections or the bimap of Google guava
But is there an implementation that helps to obtain a set of row keys from the values of table data?
I'd love to find something similar
Set<R> table.getRowsByValue( C columnKey,V value )
This should result in something like:
table.getRowsByValue("Genre","Musician"); // [David Bowie,Eddie Van Halen]
Update 1
As I mentioned earlier, there is a map implementation that allows you to retrieve keys by a given value I try to use them:
BidiMap bidiMap = new DualHashBidiMap<String,String>(table.column("Genre")); bidiMap.getKey("Musician"); // "David Bowie"
Apache colletions mode - returns only the last element
BiMap biMap = HashBiMap.create(table.column("Genre")); biMap.inverse().get("Musician");
Google guava's bimap threw a (verbose) exception:
java.lang.IllegalArgumentException: value already present: Musician
Solution
Using a regular map, I will iterate over the map Entryset(), and then pull map Entry. getKey().
Here you seem to be able to iterate over cellset() and return set < table Cell< R,V>>
In Java 8 (I hope there are no spelling mistakes, I didn't try):
table.cellSet().stream() .filter(tc -> tc.getColumnKey().equals("Director")) .collect(Collectors.toList());