目錄
1、List<Object>-->> List<Object>:去重
2、List<User> -->> List<User.getName>:提取屬性集合
3、List1<Object>-->> List2<Object>:where id = 1
4、List<User> -->> Map<User.getId, User>>:group by id,>
5、List<User> -->> Map<User.getCode, User.getValue>
1、List<Object> -->> List<Object>:去重
List根據屬性去重
//根據userid去重
userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(User :: getUserid))), ArrayList::new));
2、List<User> -->> List<User.getName>:提取屬性集合
提取對象集合中某個屬性的集合
List<User> users= new ArrayList<User>();
// 取出所有userName集合:
List<String> names = user.stream().map(User :: getName).collect(Collectors.toList());
3、List1<Object> -->> List2<Object>:where id = 1
提取所有ID==1的數據包裝爲LIST
List<InvestmentAnalysis> enterAnn = scaleOverview.stream().filter(obj ->
obj.getType().equals("企業年金")).collect(Collectors.toList());
4、List<User> -->> Map<User.getId, List<User>>:group by id
分組,Id作爲key,數據包裝成List放入value
將List數據分組後包裝成Map,某屬性作爲key【一般爲id或name】,該key下的數據提取爲List存入value
假設有實體類User,裏面有屬性id,我們將相同id的User進行分組,並存放在Map中。
Map<Integer, List<User>> map = list.stream().collect(Collectors.groupingBy(User::getId));
5、List<User> -->> Map<Integer, String>:Map<User.getCode, User.getValue>
List包裝爲某屬性作爲key,某屬性作爲value的Map,其中value可能爲null,需要做處理
Map<String, BigDecimal> aggInvMap = list.stream().collect(Collectors.toMap(AggInvAna::getTypeCode,
p -> {
BigDecimal val = p.getZb() == null ? new BigDecimal("0") : p.getZb();
return val.setScale(2, BigDecimal.ROUND_HALF_UP);
}
));
Map<String, Map<String, BigDecimal>> map = new HashMap<>();
Map<String, List<AggInvAna>> collect = mapper.queryCfgAnaGS(dto).stream().
collect(Collectors.groupingBy(AggInvAna::getManager));
for (Map.Entry<String, List<AggInvAna>> entrie: collect.entrySet()) {
String key = entrie.getKey();
List<AggInvAna> list = entrie.getValue();
Map<String, BigDecimal> aggInvMap = list.stream().collect(Collectors.toMap(AggInvAna::getTypeCode,
p -> {
BigDecimal val = p.getZb() == null ? new BigDecimal("0") : p.getZb();
return val.setScale(2, BigDecimal.ROUND_HALF_UP);
}
));
map.put(key, aggInvMap);
}