Skip to content

Instantly share code, notes, and snippets.

@brunodoamaral
Created March 1, 2015 20:59
Show Gist options
  • Save brunodoamaral/05db794e84cf0e0758b4 to your computer and use it in GitHub Desktop.
Save brunodoamaral/05db794e84cf0e0758b4 to your computer and use it in GitHub Desktop.
A simple Table for Java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* Created by Bruno on 01/03/2015.
*
* Table with type R for rows, C for columns and V for values
*
*/
public class Table <R,C,V>
{
Map<R, Map<C, V>> map ;
public Table() {
map = new HashMap() ;
}
private Map<C, V> getRowValuesInternal(R row, boolean createRow) {
Map<C, V> rowValues = map.get(row) ;
if (rowValues == null && createRow) {
rowValues = new HashMap() ;
map.put(row, rowValues) ;
}
return rowValues ;
}
public Map<C, V> getRowValues(R row) {
return getRowValuesInternal(row, false) ;
}
public boolean containsRow(R row) {
return map.containsKey(row) ;
}
public V get(R row, C column) {
if ( containsRow(row) ) {
return getRowValues(row).get(column) ;
} else {
return null ;
}
}
public void put(R row, C column, V value) {
getRowValuesInternal(row, true).put(column, value) ;
}
public Set<Map.Entry<R, Map<C, V>>> entrySet() {
return map.entrySet() ;
}
public void forEachRow(Consumer<Map.Entry<R, Map<C, V>>> consumer) {
map.entrySet().forEach(consumer) ;
}
public void forEachColumn(Consumer<Map.Entry<C, Map<R, V>>> consumer) {
this.reverseMap().entrySet().forEach(consumer);
}
private Map<C, Map<R, V>> reverseMap() {
Map<C, Map<R, V>> reverseMap = new HashMap() ;
for (Map.Entry<R, Map<C, V>> rowEntry : map.entrySet()) {
R row = rowEntry.getKey() ;
for (Map.Entry<C, V> columnEntry : rowEntry.getValue().entrySet()) {
C column = columnEntry.getKey() ;
V value = columnEntry.getValue() ;
Map<R, V> columnsMap = reverseMap.get(column) ;
if (columnsMap == null) {
columnsMap = new HashMap() ;
reverseMap.put(column, columnsMap) ;
}
columnsMap.put(row, value) ;
}
}
return reverseMap ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment