您的位置:首页 > 编程语言 > Java开发

java8新特性 --- stream(二)

2017-12-13 11:02 513 查看
2、映射

     2.1 map 利用此功能可以输出我们需要的东西

     将学生实体映射成学生姓名

List<String> names = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.map(Student::getName).collect(Collectors.toList());
     除了上面这类基础的map,java8还提供了mapToDouble(ToDoubleFunction<? super T> mapper),mapToInt(ToIntFunction<? super T> mapper),mapToLong(ToLongFunction<? super T> mapper)

     计算‘计算机科学’专业的学生年龄之和

int totalAge = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.mapToInt(Student::getAge).sum();
     使用这些数值流的好处还在于可以避免jvm装箱操作所带来的性能消耗。

     2.2 flatMap   用于合并用

    

/**
* 测试flatMap类似于addAll的功能
*/
@Test
public void flatMapTest() {
List<Integer> collected0 = new ArrayList<>();
collected0.add(1);
collected0.add(3);
collected0.add(5);
List<Integer> collected1 = new ArrayList<>();
collected1.add(2);
collected1.add(4);
collected1 = Stream.of(collected0, collected1)
.flatMap(num -> num.stream()).collect(Collectors.toList());
System.out.println(collected1);// 1,3,5,2,4
}
3、查找

     3.1 allMatch   用于检测是否全部都满足指定的参数行为,如果全部满足则返回true

     检测是否所有的学生都已满18周岁

boolean isAdult = students.stream().allMatch(student -> student.getAge() >= 18);
     3.2 anyMatch   检测是否存在一个或多个满足指定的参数行为,如果满足则返回true

      检测是否有来自武汉大学的学生

boolean hasWhu = students.stream().anyMatch(student -> "武汉大学".equals(student.getSchool()));
     3.3  noneMathch  检测是否不存在满足指定行为的元素

     检测是否不存在专业为‘计算机科学’的学生

boolean noneCs = students.stream().noneMatch(student -> "计算机科学".equals(student.getMajor()));
     3.4 findFirst 返回满足条件的第一条元素

     专业为土木工程的排在第一个学生
Optional<Student> optStu = students.stream().filter(student -> "土木工程".equals(student.getMajor())).findFirst();
     Optional 参考这一篇:Java8新特性 – Optional类

4、归约  对经过参数化操作后的集合进行进一步的运算,那么我们可用对集合实施归约操作

     
// 前面例子中的方法
int totalAge = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.mapToInt(Student::getAge).sum();
// 归约操作
int totalAge = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.map(Student::getAge)
.reduce(0, (a, b) -> a + b);

// 进一步简化
int totalAge2 = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.map(Student::getAge)
.reduce(0, Integer::sum);

// 采用无初始值的重载版本,需要注意返回Optional
Optional<Integer> totalAge = students.stream()
.filter(student -> "计算机科学".equals(student.getMajor()))
.map(Student::getAge)
.reduce(Integer::sum);  // 去掉初始值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  map flatMap reduce