Skip to content

Instantly share code, notes, and snippets.

@aaberg
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save aaberg/475f03eebcf4773cb118 to your computer and use it in GitHub Desktop.

Select an option

Save aaberg/475f03eebcf4773cb118 to your computer and use it in GitHub Desktop.
Key value list that wraps a org.sql2o.Table instance.
public class KeyValueList <E, V> extends AbstractList<Map.Entry<E, V>> {
private final Table data;
private final Class classOfE;
private final Class classOfV;
public KeyValueList(Table data, Class<E> classOfE, Class<V> classOfV) {
this.data = data;
// It is necessary to specify the class of the key and value,
// as it is not possible to get this information from java generics.
this.classOfE = classOfE;
this.classOfV = classOfV;
}
@Override @SuppressWarnings("unchecked")
public Map.Entry<E, V> get(int index) {
Row row = data.rows().get(index);
return new AbstractMap.SimpleEntry<>(
(E)row.getObject(0, classOfE),
(V)row.getObject(1, classOfV));
}
@Override
public int size() {
return data.rows().size();
}
}
@Test
public void testKeyValueList(){
final String sql =
"select * " +
"from ( " +
"select 1 id, 'row1' val " +
"from (values(0)) " +
"union select 2 id, 'row2' " +
"from (values(0)) " +
") t " +
"order by id";
final List<Map.Entry<Integer, String>> resultList;
try (Connection connection = sql2o.open()) {
resultList = new KeyValueList<>(
connection.createQuery(sql).executeAndFetchTable(),
Integer.class,
String.class
);
}
assertEquals(2, resultList.size());
Integer i = 0;
for (Map.Entry<Integer, String> entry : resultList) {
assertEquals(++i, entry.getKey());
assertEquals("row" + i, entry.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment