stream 分组 求最小值,字符串连接
public static void main(String[] arg){
InsureOrg org1= new InsureOrg();
org1.setOrgId("1");
org1.setOrgName("江苏");
org1.setAddress("中央路");
org1.setRegisterTime("2000-10-01");
org1.setOrgType("记录仪");
InsureOrg org2= new InsureOrg();
org2.setOrgId("1");
org2.setOrgName("江苏");
org2.setAddress("龙蟠路");
org2.setRegisterTime("2000-10-02");
org2.setOrgType("无人机");
InsureOrg org3= new InsureOrg();
org3.setOrgId("3");
org3.setOrgName("浙江");
org3.setAddress("南京路");
org3.setRegisterTime("2000-10-04");
org3.setOrgType("记录仪");
InsureOrg org4= new InsureOrg();
org4.setOrgId("3");
org4.setOrgName("浙江");
org4.setAddress("福建路");
org4.setRegisterTime("2000-10-07");
org4.setOrgType("记录仪");
List<InsureOrg> list = new ArrayList();
list.add(org1);
list.add(org2);
list.add(org3);
list.add(org4);
//使用stream的groupBy指定属性进行分组
List<InsureOrg> result = new ArrayList();
Map<String, List<InsureOrg>> map = list.stream().collect(Collectors.groupingBy(InsureOrg::getOrgId));
for (String key : map.keySet()) {
List<InsureOrg> value = map.get(key);
InsureOrg temp =new InsureOrg();
temp.setOrgId(key);
temp.setOrgName(value.get(0).orgName);
Optional<String> minTime = value.stream().map(InsureOrg::getRegisterTime).min(String::compareTo);
if(minTime.isPresent())
temp.setRegisterTime(minTime.get());
String address= value.stream().map(InsureOrg::getAddress).distinct().collect(Collectors.joining(", "));
temp.setAddress(address);
String type= value.stream().map(InsureOrg::getOrgType).distinct()
.collect(Collectors.joining(", "));
temp.setOrgType(type);
result.add(temp);
}
System.out.println(result.size());
}