学习Stream第二篇

309 阅读2分钟

思考一下我们使用流的过程:第一步创建流,也就是把数组,集合或文件转化为一个流;第二步使用流的中间操作,如对数据进行排序,筛选和映射;第三步终结操作,如匹配,计数等。


现在我们介绍一些新的方法:

1.IntStream mapToInt(ToIntFunction<? super T> mapper); 它把一个流映射为一个IntStream流

public class Person {
    private String name;

    private int age;

    private String course;

    public Person(String name, int age, String course) {
        this.name = name;
        this.age = age;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }
}


上面是一个简单的Person类

下面准备一个persons的集合。

Person p1 = new Person("lilei", 12, "math");
Person p2 = new Person("xiaowang", 11, "english");
Person p3 = new Person("lihei", 15, "dance");
Person p4 = new Person("wanger", 11, "CS");
Person p5 = new Person("tianer", 17, "math");

ArrayList<Person> persons = new ArrayList<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
persons.add(p5);

//求是math学科的人的年龄的和
int sum = persons.stream()
        .filter(p -> "math".equals(p.getCourse()))
        .mapToInt(Person :: getAge).sum();
System.out.println(sum);

2. <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

这个方法里面的mapper函数会应用到每个元素上,从而每个元素会产生一个新值的流,然后把这些流扁平化成一个流作为返回值。它一般用在操作维度比较深的结构如多层嵌套的数组转化为简单的形式。比如你用map把一个字符串转为了一个字符串的数组,但是你想要的结果并非一个数组形式的结果,就可以用这个方法。


同map方法一样,flatMap方法也有它的一些映射到如int,long类型的方法。

今天的学习总结就到这儿吧。