已知一个对象集合,按需求将部分属性抽取出来组成新的集合
假设已知的集合为商品详情集合
List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
1、组成单列集合 (将商品的id组成一个新的集合)
List<String> productIds = orderDetailList.stream().map(OrderDetail::getProductId).collect(Collectors.toList());
2、组成一个新的对象集合 (将商品id和数量抽取组成CartDTO的集合)
List<CartDTO> cartDTOS = orderDetailList.stream().map(e -> new CartDTO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
3、组成新的对象集合 (代码较多,在{}中操作,并return)
toMap的使用
Map<String, String> deptMap = deptList.stream().collect(Collectors.toMap(ManagementDept::getId, ManagementDept::getDName));
Map<String, CheckPlaceConfig> placeConfigMap = checkPlaceConfigs.stream().collect(Collectors.toMap(CheckPlaceConfig::getId, e -> e));
排序
appleList.sort(Comparator.comparing(Apple::getWeight)); // 排序
appleList.sort(Comparator.comparing(Apple::getWeight).reversed()); // 逆序
appleList.sort(Comparator.comparing(Apple::getWeight) // 按重量排序
.reversed() // 逆序
.thenComparing(Apple::getColor)); // 重量一样按颜色排序
List 转 Map
常用方式
代码如下:
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
收集成实体本身map
代码如下:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
分组的方法
Map<Long, List<ActivityUserMissionDO>> map = activityUserMissionDos.stream().collect(Collectors.groupingBy(ActivityUserMissionDO::getParentModuleId));
指定具体收集的map
toMap还有另一个重载方法,可以指定一个Map的具体实现,来收集数据:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}