前言:
- 在没有接触java8的时候,我们遍历一个集合都是用循环的方式,从第一条数据遍历到最后一条数据,现在思考一个问题,为什么要使用循环,因为要进行遍历,但是遍历不是唯一的方式,遍历是指每一个元素逐一进行处理(目的),而并不是从第一个到最后一个顺次处理的循环,前者是目的,后者是方式。 所以为了让遍历的方式更加优雅,出现了流(stream)!
stream的方法:
![](https://img.haomeiwen.com/i18791186/94b84ef281ba4b60)
image
这篇文章主要先讲3个常用的情景:
- 一:把list里每一个对象的某个属性值取出来放到list中
- 二:把list里每一个对象的某几个属性转成其他对象的属性并返回新的对象组成的List
- 三:把list里每一个对象拷贝到另一个同样属性的对象中并返回新的对象组成的List
public static void main(String[] args) {
List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
OrderDetail orderDetail = new OrderDetail();
orderDetail.setProductId("1");
orderDetail.setProductQuantity(1);
OrderDetail orderDetail2 = new OrderDetail();
orderDetail2.setProductId("2");
orderDetail2.setProductQuantity(2);
OrderDetail orderDetail3 = new OrderDetail();
orderDetail3.setProductId("3");
orderDetail3.setProductQuantity(3);
orderDetailList.add(orderDetail);
orderDetailList.add(orderDetail2);
orderDetailList.add(orderDetail3);
// 一:把list里每一个对象的ID取出来放到list中
List<String> productIdList = orderDetailList.stream()
.map(OrderDetail::getProductId)
.collect(Collectors.toList());
System.out.println(productIdList); // 输出 [1,2,3]
// 二:把list里每一个对象的某几个属性转成其他对象的属性
List<DecreaseStockInput> decreaseStockInputList = orderDetailList.stream()
.map(e -> new DecreaseStockInput(e.getProductId(), e.getProductQuantity()))
.collect(Collectors.toList());
System.out.println(decreaseStockInputList);
// 输出 [
// DecreaseStockInput(productId=1, productQuantity=1),
// DecreaseStockInput(productId=2, productQuantity=2),
// DecreaseStockInput(productId=3, productQuantity=3)
// ]
// 三:把list里每一个对象拷贝到另一个同样属性的对象中并返回新的对象List
List<ProductInfo> productInfoList = new ArrayList<ProductInfo>();
ProductInfo productInfo = new ProductInfo();
productInfo.setProductId("1");
productInfo.setProductName("商品1");
ProductInfo productInfo2 = new ProductInfo();
productInfo2.setProductId("2");
productInfo2.setProductName("商品2");
productInfoList.add(productInfo);
productInfoList.add(productInfo2);
List<ProductInfoOutput> productInfoOutputList =
productInfoList.stream().map(e -> {
ProductInfoOutput productInfoOutput = new ProductInfoOutput();
BeanUtils.copyProperties(e, productInfoOutput);
return productInfoOutput;
}).collect(Collectors.toList());
System.out.println(productInfoOutputList);
// 输出[
// ProductInfoOutput(productId=1, productName=商品1),
// ProductInfoOutput(productId=2, productName=商品2)
// ]
}
网友评论