關於List按V的某個屬性分組的通用代碼實現

private static Map<String, List<Object>> grouping(List<Map<String, Object>> list, String k) {
    Map<String, List<Object>> map = new TreeMap<>();
    String key;
    List<Object> listTmp = new ArrayList<>();
    for (Map<String, Object> val : list) {
        if (val.get(k) == null) {
            key = "其餘";
        } else {
            key = val.get(k).toString();
        }

        if (!map.containsKey(key)) {
            listTmp = new ArrayList<>();
            map.put(key, listTmp);
        }
        listTmp.add(val);
    }
    return map;
}
相關文章
相關標籤/搜索