【java8新特性】stream流的方式遍历集合(几个常用用法)

 前言:

在没有接触java8的时候,我们遍历一个集合都是用循环的方式,从第一条数据遍历到最后一条数据,现在思考一个问题,为什么要使用循环,因为要进行遍历,但是遍历不是唯一的方式,遍历是指每一个元素逐一进行处理(目的),而并不是从第一个到最后一个顺次处理的循环,前者是目的,后者是方式。 所以为了让遍历的方式更加优雅,出现了流(stream)!
 

stream的方法:

【java8新特性】stream流的方式遍历集合(几个常用用法)_第1张图片

这篇文章主要先讲3个常用的情景:

一:把list里每一个对象的某个属性值取出来放到list中

二:把list里每一个对象的某几个属性转成其他对象的属性并返回新的对象组成的List

三:把list里每一个对象拷贝到另一个同样属性的对象中并返回新的对象组成的List

public static void main(String[] args) {
		
	List orderDetailList = new ArrayList();
	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 productIdList = orderDetailList.stream()
			.map(OrderDetail::getProductId)
			.collect(Collectors.toList());
		
	System.out.println(productIdList);  // 输出 [1,2,3]
		
	// 二:把list里每一个对象的某几个属性转成其他对象的属性
	List 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 productInfoList = new ArrayList();
	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 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)
	//		]
}

更高级的用法后续会更新。。。

你可能感兴趣的:(Java)