java8新特性stream api如何使用

2024-10-14 10:12:53

1、介绍步骤还是结合例子来说明更容易理解一点,首先创建个List集合对象实例,添加4个用来测试的学生实例List<Stude荏鱿胫协nt> students = new ArrayList<Student>();students.add(new Student("Tom", 12, "male", 5));students.add(new Student("Lili", 11, "female", 4));students.add(new Student("John", 8, "male", 1));students.add(new Student("Lucy", 10, "female", 3));System.out.println("所有学生:");students.forEach((p) -> System.out.printf("%s;", p.getName()));先运行下,打印出所有学生名字

java8新特性stream api如何使用

3、limit/skip,limit返回前n个元素,skip则是跳过前n个元素System.out.println("梓脶阗擗最前面2个学生:");students.stream() .limit(2) .forEach((p) -> System.out.printf("%s;", p.getName()));System.out.println();System.out.println("跳过前面2个学生:");students.stream() .skip(2) .forEach((p) -> System.out.printf("%s;", p.getName()));System.out.println();运行结果如下:

java8新特性stream api如何使用

5、parallel并行模式,对于大数据量非常有用,mapToInt作用是把学生的年龄映射成int的stream,sum是计算总和System.out.println("所有学生年龄总和:");System.out.println(students.stream().parallel().mapToInt(Student::getAge).sum());运行结果如下,年龄总和为41

java8新特性stream api如何使用

7、流转换为其它数据结构,有兴趣的可以参考下面的例子测试下结果

java8新特性stream api如何使用
猜你喜欢