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

本文详细介绍Java8中Stream API的三个常见应用场景:提取List中对象的特定属性值;转换List中对象的某些属性为新对象;复制List中对象到具有相同属性的新对象,并返回新对象List。通过具体代码实例,展示Stream API如何简化集合操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 前言:

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

stream的方法:

这篇文章主要先讲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)
	//		]
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值