JDK1.8新特性Stream学习笔记

2 篇文章 0 订阅

个人学习笔记

Stream学习图

在这里插入图片描述

lambda表达式加stream,真的能一行代码给集合排序,集合类型转换,集合分组,聚合,收集,而且性能会比你自己实现高很多。Stream会收集所有中间操作,在最后终端操作的时候使用尽可能少的的循环次数一次性完成所有中间操作,你只需要提供一个比较的函数或者一些聚合分组的判断函数。这并不是为了炫技,而是有实实在在的好处的。

List<HandleProductionOrderDetail> handleDetailsOfGroupedAndSorted = allHandleProductionOrderDetails
	.stream()
	//Collectors.groupingBy对HandleProductionOrderDetail里面的多个属性进行分组,用"_"分割
	.collect(Collectors.groupingBy(detail -> detail.getDpOrderNo() + "_"
			+ detail.getDpHandleItemNo() + "_" + detail.getCalcuLength() + "_"
			+ detail.getOpenDoorWayValue() + "_" + detail.getHandleFixWayName()))
	//genHandleProdOrderDetail()构造出新的HandleProductionOrderDetail对象
	.entrySet().stream().map(entry -> genHandleProdOrderDetail(entry))
	//sorted对HandleProductionOrderDetail的属性进行分组,用::表示,后面跟着要分组的属性,thenComparing多个属性分组
	.sorted(Comparator.comparing(HandleProductionOrderDetail::getDpTypeName)
			.thenComparing(HandleProductionOrderDetail::getDpHandleItemName)
			.thenComparing(HandleProductionOrderDetail::getDeliveryDate)
			.thenComparing(HandleProductionOrderDetail::getDpOrderNo))
	//collect(Collectors.toList())返回List集合,如果toList()换成toSet(),那么就是返回Set集合
	.collect(Collectors.toList());

构造出新的HandleProductionOrderDetail对象

private HandleProductionOrderDetail genHandleProdOrderDetail(
		Entry<String, List<HandleProductionOrderDetail>> entry) {
	HandleProductionOrderDetail handleProductionOrderDetail = entry.getValue().get(0);
	int sumQty = entry.getValue().stream()
			//获得HandleProductionOrderDetail对象里的handleQuantity的值,最后用Collectors.summingInt进行合计
			.collect(Collectors.summingInt(HandleProductionOrderDetail::getHandleQuantity)).intValue();
	String remark = entry.getValue().stream().map(HandleProductionOrderDetail::getDpNo)
			.collect(Collectors.joining(","));
	handleProductionOrderDetail.setHandleQuantity(sumQty);
	handleProductionOrderDetail.setRemark(remark);
	return handleProductionOrderDetail;//返回HandleProductionOrderDetail对象
}

遍历每一个

private void freezeGeneDpPpOrder(String orderNo, boolean isFrozen) {
	//通过orderNo获取GeneralDpPpOrder集合对象
	List<GeneralDpPpOrder> ppOrders = geneDpPpOrderService.getGeneralDpPpOrderByRefOrderNo(orderNo);
	if (ppOrders != null && ppOrders.size() > 0) {
		//对每一个对象的frozen属性赋值
		ppOrders.stream().forEach(ppOrder -> ppOrder.setFrozen(isFrozen));
	}
}

A集合对象对比B集合对象(实例:图一A集合,图二B集合)
图一
在这里插入图片描述
图二
在这里插入图片描述
A集合和B集合,A集合里面的客户名称,和B集合客户名称进行一一对比,即遍历A集合的每一行,另外,还得遍历B集合的每一行,对比客户名称。

//获得A集合对象
List<FirstOrderHistoryData> firstOrderHistoryDatas = genFirstOrderHistoryDataList(sheet);
List<FirstOrderHistoryData> allHistoryDatas = firstOrderHistoryDataRepository.findAll();//找到所有的B集合对象
firstOrderHistoryDatas.stream().forEach(row -> {//遍历A集合的每一行
	FirstOrderHistoryData firstOrderHistoryData = allHistoryDatas.stream()
			.filter(hdata -> //遍历B集合的每一行
			hdata.getCustomerName().equals(row.getCustomerName())).findFirst()
			.orElse(null);//找到A集合与B集合的customerName相等的数据
	if (firstOrderHistoryData != null) {//如果找到了
		row.setId(firstOrderHistoryData.getId());//找到数据之后,设置id,因为id唯一
	}
});
//从A集合中获得的数据,保存到B集合中(根据customerName为依据),允许覆盖数据,增加新数据
firstOrderHistoryDataRepository.save(firstOrderHistoryDatas);

层层嵌套,在子对象里面的属性进行对比

//层层嵌套,寻找子对象
List<DpOrderResult> dpSplitResultsOfHandles = dpOrders.stream()
	.flatMap(order -> order.getDpOrderElements().stream())//得到dpOrders里面的子对象element
	.flatMap(element -> element.getDpOrderResults().stream())//得到element里面的子对象result
	.filter(result -> isBelongHandle(result)//找到子对象result里面的standardHandle属性符合条件的
			&& result.getStandardHandle() == StandardHandle.STANDARD.getIndex())
	.collect(Collectors.toList());

找到该对象下某个属性的集合

List<UnitMaster> allUnits = unitMasterService.getAllUnits();
	UnitMaster unit = allUnits.stream().filter(unitMaster -> unitMaster.getNo().equals(detail.getProdCountUnitNo()))
			.findFirst().orElse(null);
	if(unit != null) {
		houseCustomCabinetPpOrderReport.setProdCountUnitNo(unit.getName());
	}
		
Set<String> dpOrderNos = handleStockOutOrder.getDetails().stream()
	.filter(detail -> detail.getStkOutStatus() == OrderStatus.TO_BE_STOCKOUT.getIndex())
	//.map可以理解为构建值
	.map(HandleStockOutDetail::getDpOrderNo).collect(Collectors.toSet());
				
Set<String> parentComponentNos = parents.stream().map(ParentComponent::getParentComponentNo)
	.collect(Collectors.toSet());	

fileter过滤找到符合条件的对象

HandleStockOutDetail stkOutDetailOfNotOut = stkOutOrder.getDetails().stream()
	.filter(detail -> detail.getStkOutStatus() == OrderStatus.TO_BE_STOCKOUT.getIndex()).findFirst()
	.orElse(null);
ShipDetail shipDetail = shipOrder.getShipDetails().stream()
	.filter(detail -> detail.getOrderNo().equals(generalStockOutOrder.getOrderNo())).findFirst()
	.orElse(null);

生成新构建的对象

stockReports.stream().map(stockObj -> genStockReport(stockObj)).collect(Collectors.toList());
	
private StockReport genStockReport(Object[] stockObj) {
	StockReport stockReport = new StockReport();
	stockReport.setItemNo(stockObj[0].toString());
	stockReport.setItemFullName(stockObj[1].toString());
	stockReport.setItemTypeName(stockObj[2].toString());
	stockReport.setQuantity((float) stockObj[3]);
	stockReport.setWareHouseNo(stockObj[4].toString());
	stockReport.setWareHouseName(stockObj[5].toString());
	return stockReport;
}

分组

//entry.getValue().size() > 1过滤掉没值的,entry.getValue().get(0)取值 
List<Customer> repeatRecords = customers.stream().collect(Collectors.groupingBy(Customer::getShortName))
	.entrySet().stream().filter(entry -> entry.getValue().size() > 1).map(entry -> entry.getValue().get(0))
	.collect(Collectors.toList());

List<DpProdScheduleReport> scheduleReports = getDpProdScheduleReports(operatorNo, orderNos).stream()
					.sorted(Comparator.comparing(DpProdScheduleReport::getOrderStatus)
							.thenComparing(DpProdScheduleReport::getProdDeliveryDate, Comparator.reverseOrder())//倒序
							.thenComparing(DpProdScheduleReport::getOrderNo, Comparator.reverseOrder())
							.thenComparing(DpProdScheduleReport::getPpOrderType))
					.collect(Collectors.toList());

**********先对A集合排序,再根据A集合里面的对象进行排序。比如有多个学校,先根据学校名称排序,然后再根据学校里面的班级,进行排序

DispatchRouting dispatchRouting = dispatchRoutingRepo.findById(id).orElse(null);
List<ProcessSeqNum> processSeqNums;
if (dispatchRouting != null && dispatchRouting.getProcessSeqNums() != null) {
	dispatchRouting.getProcessSeqNums().size();
	processSeqNums = dispatchRouting
			.getProcessSeqNums().stream().sorted(Comparator.comparing(ProcessSeqNum::getSeqNum)
					.thenComparing(e -> e.getProcess().getNo(), Comparator.naturalOrder()))
			.collect(Collectors.toList());
	dispatchRouting.setProcessSeqNums(processSeqNums);
}
return dispatchRouting;

按照dpNo大小来排序

List<GeneralDpPpOrderDetail> details = getGeneDpPpOrderDetails(dpOrder).stream().sorted(
	(a, b) -> (Integer.parseInt(a.getdPNo().substring(1)) - Integer.parseInt(b.getdPNo().substring(1))))
	.collect(Collectors.toList());	

A集合和B集合中,共同的属性,相互比较(其中含null)并赋值

List<PaymentMethod> payments = paymentMethodRepo.findAll();
List<String> monthPayNos = mouthGoodsReceipts.stream().map(monthGood -> monthGood.getPayNo())
	.collect(Collectors.toList());
List<String> payNos = payments.stream().map(pay -> pay.getNo()).collect(Collectors.toList());
List<String> otherNos = payNos.stream().filter(payNo -> !monthPayNos.contains(payNo)).collect(Collectors.toList());
for (int i = 0; i < otherNos.size(); i++) {
GoodsReceiptReport goodsReceiptReport = new GoodsReceiptReport();
goodsReceiptReport.setPayNo(otherNos.get(i));
mouthGoodsReceipts.add(goodsReceiptReport);
}
List<GoodsReceiptReport> sortGoodsReceiptReports = mouthGoodsReceipts.stream()
	.sorted(Comparator.comparing(GoodsReceiptReport::getPayNo)).collect(Collectors.toList());

遍历集合,赋值

orderMonthReports.stream().forEach(detail -> {
		detail.setAmountSum(detail.getPositiveAmount() + detail.getReturnAmount());
		detail.setAreaSum(detail.getPositiveArea() + detail.getReturnArea());
		detail.setNumSum(detail.getPositiveOrderNoNum() + detail.getReturnOrderNoNum());
	});

在集合的集合赋值

List<MaterialPurchaseElement> materialPurchaseElements = houseCustomOrder.getMaterialPurchaseElements()
					.stream().map(data -> setItemNo(data, itemMaster)).collect(Collectors.toList());
			houseCustomOrder.setMaterialPurchaseElements(materialPurchaseElements);
			houseCustomOrderRepository.save(houseCustomOrder);
private MaterialPurchaseElement setItemNo(MaterialPurchaseElement materialPurchaseElement, ItemMaster itemMaster) {
		if (itemMaster.getItemName().equals(materialPurchaseElement.getItemName())
				&& itemMaster.getSpec().equals(materialPurchaseElement.getSpec())) {
			materialPurchaseElement.setItemNo(itemMaster.getItemNo());
			return materialPurchaseElement;
		}
		return materialPurchaseElement;
	}

去掉重复的

List<HouseMaterialSpecPropStruc> houseMaterialSpecPropStrucs = materialPurchaseElements.stream()
					.map(ele -> genHouseMaterialSpecPropStruc(ele)).filter(data -> {
						if (fullNames.contains(data.getFullName())) {
							throw new DoorMaterialDataException("有重复的物料:" + data.getFullName());
						} else {
							fullNames.add(data.getFullName());
							return true;
						}
					}).collect(Collectors.toList());
List<String> fullNames = new ArrayList<>();
			List<HouseDpSpecPropStruc> houseDpSpecPropStrucs = dpPurchaseElements.stream()
					.map(this::genHouseDpSpecPropStruc).filter(data -> {
						if (fullNames.contains(data.getFullName())) {
							return false;
						} else {
							fullNames.add(data.getFullName());
							return true;
						}
					}).collect(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

exodus3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值