采用stream流处理集合 实现list数据的封装

for循环方式

List<CategoryBrand> categoryBrandList = new ArrayList<>();
	for (Long categoryId : categoryIds) {
		CategoryBrand tbCategoryBrand = new CategoryBrand();
		tbCategoryBrand.setCategoryId(categoryId);
		tbCategoryBrand.setBrandId(tbBrandId);
		categoryBrandList.add(tbCategoryBrand);
	}

stream流结合lambda方式

List<CategoryBrand> categoryBrandList = categoryIds.stream().map(categoryId -> {
			CategoryBrand categoryBrand = new CategoryBrand();
			categoryBrand.setBrandId(tbBrand.getId());
			categoryBrand.setCategoryId(categoryId);
			return categoryBrand;
		}).collect(Collectors.toList());

测试类

/**
 * @author: mryhl
 * @date: Created in 2020/11/16 9:11
 * @description:
 */
public class StreamTest {
	/*
	* 将Long集合中的每个元素输出
	*/
	@Test
	public void test() throws Exception {
		List<Long> longs = Arrays.asList(10L, 30L, 34L, 37L);
		for (Long aLong : longs) {
			System.out.println(aLong);
		}
		
		// 采用stream输出
		longs.stream().forEach(long1->{
			System.out.println(long1);
		});
		longs.stream().forEach(System.out::print);
	}
	
	/*
	* 
	* 将Long集合转为String类型
	*
	*/
	
	@Test
	public void test2() throws Exception {
		List<Long> longs = Arrays.asList(10L, 30L, 34L, 37L);
		longs.stream().map(abc->{
			return abc.toString();
		}).collect(Collectors.toList());
		
		longs.stream().map(Object::toString).collect(Collectors.toList());
		
	}
}

总结

使用jdk8的lambda新特性,简化了循环赋值的方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr.YHL

谢谢您的肯定

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

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

打赏作者

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

抵扣说明:

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

余额充值