学习了groupingBy的用法,在处理List
public static void main(String[] args){
String data = "[{\"codeType\":\"ALRAM\",\"code\":\"1\",\"name\":\"普通告警\",\"sortId\":\"1\"},{\"codeType\":\"ALRAM\",\"code\":\"2\",\"name\":\"中级告警\",\"sortId\":\"2\"},{\"codeType\":\"ALRAM\",\"code\":\"3\",\"name\":\"严重告警\",\"sortId\":\"3\"},{\"codeType\":\"ALRAM\",\"code\":\"4\",\"name\":\"特级告警\",\"sortId\":\"4\"},{\"codeType\":\"NOTICE\",\"code\":\"1\",\"name\":\"短信通知\",\"sortId\":\"1\"},{\"codeType\":\"NOTICE\",\"code\":\"2\",\"name\":\"邮箱通知\",\"sortId\":\"2\"},{\"codeType\":\"NOTICE\",\"code\":\"3\",\"name\":\"微信消息通知\",\"sortId\":\"3\"}]";
JSONArray items = JSON.parseArray(data);
Map> codeType = ListUtils.emptyIfNull(items).stream()
.map(e -> (JSONObject) e)
.collect(Collectors.groupingBy(e -> MapUtils.getString(e, "codeType")));
System.out.println(JSON.toJSONString(codeType));
}
结果:
{
"NOTICE": [{
"code": "1",
"codeType": "NOTICE",
"sortId": "1",
"name": "短信通知"
}, {
"code": "2",
"codeType": "NOTICE",
"sortId": "2",
"name": "邮箱通知"
}, {
"code": "3",
"codeType": "NOTICE",
"sortId": "3",
"name": "微信消息通知"
}],
"ALRAM": [{
"code": "1",
"codeType": "ALRAM",
"sortId": "1",
"name": "普通告警"
}, {
"code": "2",
"codeType": "ALRAM",
"sortId": "2",
"name": "中级告警"
}, {
"code": "3",
"codeType": "ALRAM",
"sortId": "3",
"name": "严重告警"
}, {
"code": "4",
"codeType": "ALRAM",
"sortId": "4",
"name": "特级告警"
}]
}
这结果顺序发生了变化,那该如何处理,保持内容不变呢?
public static void main(String[] args){
String data = "[{\"codeType\":\"ALRAM\",\"code\":\"1\",\"name\":\"普通告警\",\"sortId\":\"1\"},{\"codeType\":\"ALRAM\",\"code\":\"2\",\"name\":\"中级告警\",\"sortId\":\"2\"},{\"codeType\":\"ALRAM\",\"code\":\"3\",\"name\":\"严重告警\",\"sortId\":\"3\"},{\"codeType\":\"ALRAM\",\"code\":\"4\",\"name\":\"特级告警\",\"sortId\":\"4\"},{\"codeType\":\"NOTICE\",\"code\":\"1\",\"name\":\"短信通知\",\"sortId\":\"1\"},{\"codeType\":\"NOTICE\",\"code\":\"2\",\"name\":\"邮箱通知\",\"sortId\":\"2\"},{\"codeType\":\"NOTICE\",\"code\":\"3\",\"name\":\"微信消息通知\",\"sortId\":\"3\"}]";
JSONArray items = JSON.parseArray(data);
Map> alram = ListUtils.emptyIfNull(items).stream()
.map(e -> (JSONObject) e)
.collect(Collectors.groupingBy(e -> MapUtils.getString(e, "codeType"),
LinkedHashMap::new,
Collectors.toCollection(ArrayList::new)));
System.out.println(JSON.toJSONString(alram));
}
结果:
{
"ALRAM": [{
"code": "1",
"codeType": "ALRAM",
"sortId": "1",
"name": "普通告警"
}, {
"code": "2",
"codeType": "ALRAM",
"sortId": "2",
"name": "中级告警"
}, {
"code": "3",
"codeType": "ALRAM",
"sortId": "3",
"name": "严重告警"
}, {
"code": "4",
"codeType": "ALRAM",
"sortId": "4",
"name": "特级告警"
}],
"NOTICE": [{
"code": "1",
"codeType": "NOTICE",
"sortId": "1",
"name": "短信通知"
}, {
"code": "2",
"codeType": "NOTICE",
"sortId": "2",
"name": "邮箱通知"
}, {
"code": "3",
"codeType": "NOTICE",
"sortId": "3",
"name": "微信消息通知"
}]
}
对于List