如果你使用的是Java 8或更高版本,还可以利用Comparator.comparing
来简化代码:
根据集合某个字段进行倒序排序
list.sort(Comparator.comparing(BaseResponseDTO::getCode).reversed());
顺序排序
list.sort(Comparator.comparing(BaseResponseDTO::getCode));
转换成新对象操作
List<NewList> collect = OldList.stream().map(s -> {
NewList n = new NewList();
BeanUtils.copyProperties(s, n);
n.setIsDeleted(0);
return n;
}).collect(Collectors.toList());
校验数据是否存在
/**
* 校验数据是否已存在数据库
*/
public void contrastData(List<ItemBO> request) {
Map<String, ItemDTO> itemMap = getItemMap(request);
request.forEach(s->{
ItemDTO item = itemMap.get(s.getItemCode());
if (itemPrice == null) {
System.out.println("===========数据不存在===========");
} else {
System.out.println("===========数据存在===========");
}
});
}
private Map<String, ItemDTO> getItemMap(List<ItemBO> request) {
List<String> itemCodes = request.stream()
.map(ItemBO::getItemCode)
.filter(StringUtils::hasText)
.distinct()
.collect(Collectors.toList());
ItemQuery query = new ItemQuery();
query.setItemCodes(itemCodes);
List<ItemDTO> itemList = itemService.queryItems(query);
if (itemList.isEmpty()) {
log.debug("获取数据失败,根据编码找不到对应数据");
throw new ApplicationException(CommonError.SYS_ERROR);
}
return itemList.stream().
collect(Collectors.toMap(ItemDTO::getItemCode, Function.identity(), (e, r) -> e));
}