Last active
August 29, 2015 14:07
-
-
Save aaberg/475f03eebcf4773cb118 to your computer and use it in GitHub Desktop.
Key value list that wraps a org.sql2o.Table instance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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