Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class Main { /** * pre: takes a valid resultSet List, a columnName to group by<br> * post: separates the list into a List of List with each sub-list having the * same columnName value sorted by the natural comparator * * @param resultSet * @param columnName * @return null if resultSet is null */ @SuppressWarnings("rawtypes") public static List<List<Map>> splitSqlList(List<Map> resultSet, String columnName) { return splitSqlList(resultSet, columnName, null); } /** * * pre: takes a valid resultSet List, a columnName to group by, a valid * comparator for the columnName's value<br> * post: separates the list into a List of List with each sub-list having the * same columnName value sorted by the keyComparator * * @param resultSet * @param columnName * @param keyComparator * @return null if resultSet is null */ @SuppressWarnings("rawtypes") public static List<List<Map>> splitSqlList(List<Map> resultSet, String columnName, Comparator keyComparator) { if (resultSet == null) return null; Map<Object, List<Map>> map = sqlMapListToMap(resultSet, columnName); Set keys = map.keySet(); Object[] keyArray = keys.toArray(); if (keyComparator == null) { Arrays.sort(keyArray); } else { Arrays.sort(keyArray, keyComparator); } List<List<Map>> rs = new ArrayList<List<Map>>(keyArray.length); for (Object key : keyArray) { rs.add(map.get(key)); } return rs; } /** * * pre : resultSet must be a valid List<Map> <br> * post : a Map<columnName, List of same columnName> * * @param <K> * @param resultSet * result set from sql. no need order by * @param columnName * the column name that need to group by * @return null if resultSet is null */ @SuppressWarnings("rawtypes") public static <K> Map<K, List<Map>> sqlMapListToMap(List<Map> resultSet, String columnName) { if (resultSet == null) return null; Map<K, List<Map>> rs = new HashMap<K, List<Map>>(); for (Map<?, ?> map : resultSet) { K colValue = (K) map.get(columnName); List<Map> inMap = rs.get(colValue); if (inMap == null) inMap = new ArrayList<Map>(); inMap.add(map); rs.put(colValue, inMap); } return rs; } }