CoalescingDecorator { public static QueryResults coalesce(QueryResults queryResults, String keyColumnName) { final Map<String, List<Object>> resultsMap = queryResults.copyData(); final Map<String, List<Object>> combinedMap = newEmptyResultMap(resultsMap); List<Object> keyColumn = queryResults.getValues(keyColumnName); List<Object> distinctKeys = keyColumn.stream() .distinct() .collect(Collectors.toList()); distinctKeys.forEach(key -> { Map<String, List<Object>> rows = extractRowsWithSameKey(resultsMap, keyColumn, key); if (rows.values().iterator().next().size() == 1) { addRowToMap(combinedMap, rows); } else { Map<String, Object> row = combineRows(rows); addNewRowToMap(combinedMap, row); } }); return new QueryResults(combinedMap); }  static QueryResults coalesce(QueryResults queryResults, String keyColumnName);  }
@Test public void test01() { Map<String, List<Object>> data = new HashMap<>(); data.put("Foo", Lists.newArrayList(1, 1, 3, 3, 4)); data.put("Bar", Lists.newArrayList("1a", "1b", "3a", "3b", "4a")); QueryResults queryResults = new QueryResults(data); QueryResults cqr = CoalescingDecorator.coalesce(queryResults, "Foo"); assertEquals(cqr.getColumns(), 2); assertEquals(cqr.getRows(), 3); }