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新特性,简化了循环赋值的方式
该博客探讨了如何利用Java 8的Lambda表达式和Stream API来简化传统的for循环,通过示例展示了在创建List<CategoryBrand>时,如何优雅地转换和收集数据。测试类进一步展示了Lambda在遍历和转换Long集合到其他类型时的运用。
3302

被折叠的 条评论
为什么被折叠?



