
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.映射
如果想通过某种操作把一个流中的元素转化成新的流中的元素,可以使用 map() 方法。
publicclassMapStreamDemo{
publicstaticvoidmain(String[]args){
List<String>list=newArrayList<>();
list.add("周杰伦");
list.add("王力宏");
list.add("陶喆");
list.add("林俊杰");
Stream<Integer>stream=list.stream().map(String::length);
stream.forEach(System.out::println);
}
}
2.排序
publicvoidtest3(){
//(1)自然排序
List<Integer>list=Arrays.asList(4,3,7,9,12,8,10,23,2);
Stream<Integer>stream=list.stream();
stream.sorted().forEach(System.out::println);
//(2)对象排序:对象类可以先实现comparable接口,或者是直接指定
//第一种:先实现compable接口
List<Student>studentList=StudentData.getStudents();
studentList.stream().sorted().forEach(System.out::println);
//第二种:直接指定comparable
List<Student>studentList1=StudentData.getStudents();
studentList1.stream()
.sorted((e1,e2)->Integer.compare(e1.getAge(),e2.getAge()))
.forEach(System.out::println);
}
3.组合
reduce() 方法的主要作用是把 Stream 中的元素组合起来,它有两种用法:
Optionalreduce(BinaryOperatoraccumulator)
没有起始值,只有一个参数,就是运算规则,此时返回 Optional。
Treduce(Tidentity,BinaryOperatoraccumulator)
有起始值,有运算规则,两个参数,此时返回的类型和起始值类型一致。
publicclassReduceStreamDemo{
publicstaticvoidmain(String[]args){
Integer[]ints={0,1,2,3};
List<Integer>list=Arrays.asList(ints);
Optional<Integer>optional=list.stream().reduce((a,b)->a+b);
Optional<Integer>optional1=list.stream().reduce(Integer::sum);
System.out.println(optional.orElse(0));
System.out.println(optional1.orElse(0));
intreduce=list.stream().reduce(6,(a,b)->a+b);
System.out.println(reduce);
intreduce1=list.stream().reduce(6,Integer::sum);
System.out.println(reduce1);
}
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容