在steam流中给list元素设置序号
参考资料地址1:
数组方式
参考资料地址2:
AtomicInteger方式
测试代码
/**
* lambda 表达式中设置序号
*/
@Test
public void test6() {
//基础数据准备
List<NumStudent> list = Arrays.asList(new NumStudent(null, "张三", 18), new NumStudent(null, "李四", 19), new NumStudent(null, "李无", 20));
//需求根据年龄大小排序并设置序号
//1 利用数组
//int[] index={1};
//list.stream().sorted(Comparator.comparing(NumStudent::getAge)).forEach(s -> s.setNum(index[0]++));
//2 利用AtomicInteger
AtomicInteger index = new AtomicInteger();
list.stream().sorted(Comparator.comparing(NumStudent::getAge)).forEach(s->s.setNum(index.incrementAndGet()));
System.out.println(list);
//[StreamTest.NumStudent(num=1, name=张三, age=18), StreamTest.NumStudent(num=2, name=李四, age=19), StreamTest.NumStudent(num=3, name=李无, age=20)]
}
steam流.peek(中间操作) 使用示例
/**
* peek(中间操作) 使用示例
*/
@Test
public void test7() {
List<Student> list = Arrays.asList(new Student("张三", 18), new Student("李四", 19));
//年龄脱敏 并做一些其他处理(略)
List<Student> resultList = list.stream().peek(s -> s.setAge(null)).collect(Collectors.toList());
System.out.println(resultList);
//[StreamTest.Student(name=张三, age=null), StreamTest.Student(name=李四, age=null)]
}