目前的项目有这么一个需求,需要根据List中,HashMap的key进行重新分组(key是固定的几个),将key相同的HashMap放入同一个List中,并且可以对这个List的大小进行控制,将这个List继续拆分成若干个List的集合。
看例子:希望能根据List中,HashMap的key进行分组,得到的结果是一个Map,分别以List中的Map的key为key,值是一个List集合,List中是多个 以3个key相同的Map为一组,放入一个List中 的List。
public static void main(String[] args) {
List<HashMap<String, String>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
HashMap<String, String> param = new HashMap<>();
if (i % 2 == 0) {
param.put("key", "key1");
param.put("value1", "value1" + i);
param.put("value2", "value2" + i);
} else {
param.put("key", "key2");
param.put("value1", "value1" + i);
param.put("value2", "value2" + i);
}
list.add(param);
}
HashMap<String, String> param = new HashMap<>();
param.put("new", "newKey");
param.put("value", "newValue");
list.add(param);
Map<String, List<List<HashMap<String, String>>>> splitList = splitList(list, 3);
System.out.println(splitList);
}
splitList
方法:
private static Map<String, List<List<HashMap<String, String>>>> splitList(List<HashMap<String, String>> clientId,
int count) {
Map<String, List<List<HashMap<String, String>>>> map = new HashMap<>();
map.put("key1", new ArrayList<List<HashMap<String, String>>>());
map.put("key2", new ArrayList<List<HashMap<String, String>>>());
map.put("new", new ArrayList<List<HashMap<String, String>>>());
for (HashMap<String, String> hashMap : clientId) {
String key = null;
if (hashMap != null && "key1".equals(hashMap.get("key"))) {
key = "key1";
} else if (hashMap != null && "key2".equals(hashMap.get("key"))) {
key = "key2";
} else {
key = "new";
}
if (map.get(key).size() == 0 || map.get(key).get(map.get(key).size() - 1).size() == count) {
map.get(key).add(new ArrayList<HashMap<String, String>>());
}
map.get(key).get(map.get(key).size() - 1).add(hashMap);
}
return map;
}
经过格式化的结果:
{
key1=[
[
{
value2=value20,
value1=value10,
key=key1
},
{
value2=value22,
value1=value12,
key=key1
},
{
value2=value24,
value1=value14,
key=key1
}
],
[
{
value2=value26,
value1=value16,
key=key1
},
{
value2=value28,
value1=value18,
key=key1
}
]
],
key2=[
[
{
value2=value21,
value1=value11,
key=key2
},
{
value2=value23,
value1=value13,
key=key2
},
{
value2=value25,
value1=value15,
key=key2
}
],
[
{
value2=value27,
value1=value17,
key=key2
},
{
value2=value29,
value1=value19,
key=key2
}
]
],
new=[
[
{
new=newKey,
value=newValue
}
]
]
}