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新特性,简化了循环赋值的方式