
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.映射
如果想通过某种操作把一个流中的元素转化成新的流中的元素,可以使用 map() 方法。
1 2 3 4 5 6 7 8 9 10 11 | public class MapStreamDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add( "周杰伦" );
list.add( "王力宏" );
list.add( "陶喆" );
list.add( "林俊杰" );
Stream<Integer> stream = list.stream().map(String::length);
stream.forEach(System.out::println);
}
}
|
2.排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public void test3(){
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);
List<Student> studentList = StudentData.getStudents();
studentList.stream().sorted().forEach(System.out::println);
List<Student> studentList1 = StudentData.getStudents();
studentList1.stream()
.sorted((e1,e2)-> Integer.compare(e1.getAge(),e2.getAge()))
.forEach(System.out::println);
}
|
3.组合
reduce() 方法的主要作用是把 Stream 中的元素组合起来,它有两种用法:
1 | Optional reduce(BinaryOperator accumulator)
|
没有起始值,只有一个参数,就是运算规则,此时返回 Optional。
1 | T reduce(T identity, BinaryOperator accumulator)
|
有起始值,有运算规则,两个参数,此时返回的类型和起始值类型一致。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class ReduceStreamDemo {
public static void main(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));
int reduce = list.stream().reduce(6, (a, b) -> a + b);
System.out.println(reduce);
int reduce1 = list.stream().reduce(6, Integer::sum);
System.out.println(reduce1);
}
}
|
以上就是关于java Stream映射、排序和组合的操作方法介绍,根据上面的简单分析运行代码节课实现,下次遇到这类问题,可以考虑下使用Stream来解决。