jdk1.8出了很多新特性,对集合操作很多,整理了一下方法,供大家使用
List转Map集合
Map<String,MaterialSupplier> map = materialSupplierList.stream().collect(Collectors.toMap(MaterialSupplier::getMaterialCode, supplier -> supplier));
List转List集合
List<Long> aggregationItemIdList= resultList.stream().map(PlanAggregationItemListVO::getId).collect(Collectors.toList());
List转Set集合
Set<String> materialCodeSet = planItemList.stream().map(PlanItemVO::getMaterialCode).collect(Collectors.toSet());
List对象属性拼接成字符串,逗号分割
String stationCodes = dataList.stream().map(Station::getStationCode).collect(Collectors.joining(","));
filter过滤组成新的集合
List<StockTransferOrderStatus> statusList = new ArrayList<>();
List<StockTransferOrderStatus> suspended = statusList.stream().filter(status -> status == StockTransferOrderStatus.SUSPENDED).collect(Collectors.toList());
List<UsagePrice> prices = pricelist.stream().filter(usagePrice -> {
if (periodBeginTime.isAfter(usagePrice.getEffectBeginTime()) &&
periodBeginTime.isBefore(usagePrice.getEffectEndTime())) {
return true;
}
return false;
}).collect(Collectors.toList());
分组
Map<Long, List<ShippingBatchItem>> groupMap = batchItemListFiler.stream().collect(Collectors.groupingBy(ShippingBatchItem::getShippingBatchId));
//数量累加求和场景1 -int 求和
Long shouldCountSum = asnItems.stream().map(OutBoundShippingNoticeItemPo::getCurrQuantity).reduce(Long::sum).get();
//数量累加求和场景2 -BigDecimal求和
BigDecimal result2 = userList.stream()
// 将user对象的age取出来map为Bigdecimal
.map(User::getAge)
// 使用reduce()聚合函数,实现累加器
.reduce(BigDecimal.ZERO,BigDecimal::add);
List<ReceiptRecordPo> receiptRecordPos = new ArrayList<>();
goodsReciptEventList.stream().forEach(item -> receiptRecordPos.add(ReceiptRecordPo.build(userName, item, objectMapper)));
//MAP
Map<Long, ReceiptItemPo> receiptItemPoMap = receiptItemList.stream().collect(Collectors.toMap(ReceiptItemPo::getId, item -> item));
Map<Long,UnifiedInventoryEs> map = esList.stream().collect(Collectors.toMap(UnifiedInventoryEs::getUnifiedInventoryId, Function.identity()));
//集合快速过滤设值
list.stream().forEach(item-> {
item.setEnabledName(item.getEnabled() ? "启用":"禁用");
});
//按照集合里的参数 拼接成目标集合
List<String> improtSnList = list.stream().map(d ->d.getMaterialCode()+"_"+d.getMaterialSn()).collect(Collectors.toList());
//集合生成另外一个集合
List<BillingItemDailyPrivate> dailyPrivateList = usagePrivateList.stream().map(usagePrivate -> {
BillingItemDailyPrivate dailyPrivate = new BillingItemDailyPrivate();
BeanUtils.copyProperties(usagePrivate, dailyPrivate);
return dailyPrivate;
}).collect(Collectors.toList());
//通过条件过滤其中数据,再拼装成集合
List<RmaReturnDetailSn> changePnList = rmaReturnDetailSnList.stream().filter(iteam ->NoRmaReasonDetailTypeEnum.MIX.getType().equals(iteam.getNoRmaReasonDetailType()) && !iteam.getMaterialCode().equals(iteam.getMixMaterialCode())).collect(Collectors.toList());
//将集合转成另外一种对象集合
List<UpdateMaterialCodeBySn> repairOrderSnTempList = changePnList.stream().map(RmaReturnDetailSn::buildUpdateMaterialCodeBySn).collect(Collectors.toList());
//List对象转换成map对象
private Map<Long, List<CloudEntryProjectBindingDto>> getRmProjectIdAndBindingMap(List<CloudEntryProjectBindingDto> rmProjectBindingDtoList) {
return rmProjectBindingDtoList ==null?null:rmProjectBindingDtoList.stream().collect(Collectors.toMap(CloudEntryProjectBindingDto::getProjectId, s -> {
List<CloudEntryProjectBindingDto> l = new ArrayList<>();
l.add(s);
return l;
}, (List<CloudEntryProjectBindingDto> s1, List<CloudEntryProjectBindingDto> s2) -> {
s1.addAll(s2);
return s1;
}));
}
//集合中按照某个字段值正序排列集合对象
List<BillingRealCostDto> sorted = realCostDtos.stream().sorted(Comparator.comparingInt(BillingRealCostDto::getMonth)).collect(toList());
//按照id集合过滤对象集合返回新的集合
returnList = proxyDtos.stream().filter(proxyDto->{
for(Long id:idList){
if(proxyDto.getId().equals(id)){
return true;
}
}
return false;
}).collect(Collectors.toList());
```java
// 集中按照其中对象的某一个字段分组统计数
// 按产品属性编码分组统计对应的费用总和
List<BillingReportMonthlyVo> list= new ArrayList();
List<ChartDto> productBillingList = list.stream()
.filter(i -> i.getMonth().equals(month)) // 筛选数据,不需要可以删掉
.collect(Collectors.groupingBy(
BillingReportMonthlyVo::getPmsProductCode,//产品编码
Collectors.reducing(
BigDecimal.ZERO,
BillingReportMonthlyVo::getRealCost,//费用汇总
BigDecimal::add
)
))
.entrySet()
.stream()
.map(entry -> new ChartDto(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
@Data
public class ChartDto {
private String name;
private Object value;
public ChartDto(String name, Object value) {
this.name = name;
this.value = value;
}
}
//对象通过属性唯一值,快速从集合中完成取值:
```java
SystemBasic systemBasic = null
List<SystemBasic> localExsitSystemFields = new ArrayList();
systemBasic.setSystemId(localExsitSystemFields.stream()
.filter(exsitSystemField -> exsitSystemField.getSystemCode().equals(systemFieldDto.getSystem_Code()))
.map(SystemBasic::getSystemId)
.findFirst().get());
//两个对象集合根据ID属性完成其他参数的赋值
List<Person> source = new ArrayList<>();
source.add(new Person(1, "Alice", 25));
source.add(new Person(2, "Bob", 30));
List<Person> target = new ArrayList<>();
target.add(new Person(1, "", 0));
target.add(new Person(2, "", 0));
// 根据 ID 匹配并赋值
for (Person srcPerson : source) {
Optional<Person> targetPerson = target.stream()
.filter(t -> t.getId() == srcPerson.getId())
.findFirst();
targetPerson.ifPresent(t -> {
t.setName(srcPerson.getName());
t.setAge(srcPerson.getAge());
});
}
// 输出结果
target.forEach(System.out::println);
}
}
//通过List对象集合中某参数,快速返回该参数对应的其他信息
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 1),
new Person("Bob", 2),
new Person("Charlie", 3)
);
String targetName = "Bob";
Optional<Integer> id = people.stream()
.filter(person -> person.getName().equals(targetName))
.map(Person::getId)
.findFirst();
id.ifPresentOrElse(
i -> System.out.println("ID of " + targetName + ": " + i),
() -> System.out.println(targetName + " not found.")
);
}
static class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
}
List对象集合中根据对象几个属性组成唯一值去重:
//存在重复对象的集合
List<ProjectVdcRelation> addProjectVdcRelations = new ArrayList<>();
//addProjectVdcRelations.add(xxx);
//....
//去除重复对象的逻辑
Map<String, ProjectVdcRelation> distinctMap = addProjectVdcRelations.stream()
.collect(Collectors.toMap(
//根据不同的属性灵活处理,这个是根据TenantId、ProjectId和VdcId三个属性组成的字符串构成唯一值
o -> String.valueOf(o.getTenantId())+"-"+ String.valueOf(o.getProjectId()) +"-"+ String.valueOf(o.getVdcId()), // key generator
Function.identity(), // value mapper
(oldValue, newValue) -> oldValue // merge function
));
//去重后的对象
List<ProjectVdcRelation> distinctList = new ArrayList<>(distinctMap.values());
//保存去重后的对象
xxxService.saveBatch(distinctList);