1:根据某一个属性对List集合进行分组
有一个发邮件的需求,从数据库查询返回需要发送的数据,返回的数据类型是List<Map<String, Object> 例如返回的数据格式如下:
对于同一个收件人,我们的需求不是给这个人发送两封邮件,而是发送一封包含这个人的所有的数据,邮件内容以表格的形式展示这个人应该看到属于他的所有业务数据内容。
所以我们需要对返回的数据进行加工, 按照mail属性进行分组,转化成Map<String,List<Map<String, Object>>这种格式,就可以统计出每个收件人应该收到多少条数据。 分组代码示例如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListGroupBy {
public static void main(String[] args) {
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> data = new HashMap<>();
data.put("mail", "123456@qq.com");
data.put("riskId", 1);
data.put("money", 10);
resultList.add(data);
data = new HashMap<>();
data.put("mail", "123456@qq.com");
data.put("riskId", 2);
data.put("money", 20);
resultList.add(data);
data = new HashMap<>();
data.put("mail", "456789@qq.com");
data.put("riskId", 3);
data.put("money", 100);
resultList.add(data);
data = new HashMap<>();
data.put("mail", "456789@qq.com");
data.put("riskId", 4);
data.put("money", 200);
resultList.add(data);
// 按照email分组 转化成 mail->list<Map>
Map<String, List<Map<String, Object>>> emailMapping = new HashMap<>();
String mail = "";
for (int i = 0; i < resultList.size(); i++) {
mail = (String) resultList.get(i).get("mail");
List<Map<String, Object>> groupInfoList = emailMapping.get(mail);
if (groupInfoList == null) {
groupInfoList = new ArrayList<>();
emailMapping.put(mail, groupInfoList);
}
groupInfoList.add(resultList.get(i));
}
System.err.println(emailMapping);
}
}
运行结果 转化成如下格式:
总结
对List集合按照某一个属性进行分组,类似数据库语句的group by,其中List的泛型不一定是Map,可以是自定义对象,对应修改代码就行。