通过流操作处理list嵌套map类型的数据并对其进行分组,首先用CollectorBy.GroupBy方法进行分组,将list拆分为HashMap的分组形式,但HashMap是无序的,所以需要转为LinkedHashMap的形式。
LinkedHashMap是HashMap的子类,是双向链表形式的HashMap,保证了有序性。
Class LinkedHashMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
java.util.LinkedHashMap<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values
All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>
网上大部分的解决方法都是用对象封装,这里放一个不用对象的方法,轻喷。
//数据
List<Map<String,String>> list = listItem
Map<String, List<Map<String, String>>> res = list.stream().
collect(Collectors.groupingBy(sortUtil::getMapkey, LinkedHashMap::new, Collectors.toList()));
//sortUtil是当前类的类名,调用getmapkey方法获取分组的关键字
Map的get方法
private static String getMapkey(Map<String,String> map) {
return map.get("Key").toString();
}