Java8 Stream常用api总结(一)

以学生对象为例,列举常见的一些使用场合,具体如下:

public class StreamLearn {

    private static List<Student> list;
    static {
        list = new ArrayList<>();
        list.add(new Student(1, "小明", 18, 85L));
        list.add(new Student(2, "张三", 19, 81L));
        list.add(new Student(3, "李四", 20, 79L));
        list.add(new Student(4, "王二", 15, 90L));
        list.add(new Student(4, "王三", 18, 90L));
    }

    public static void main(String[] args) {
        //需求1:筛选出成年人(年龄大于等于18) (filter、collect)
        List<Student> collect = list.stream().filter(student -> student.getAge() >= 18).collect(Collectors.toList());
        System.out.println(collect);

        //需求2:只要成年人的名字(filter、map、collect)
        List<String> collect1 = list.stream().filter(student -> student.getAge() >= 18).map(Student::getName).collect(Collectors.toList());
        System.out.println(collect1);

        //需求3:按照成绩排个序(sorted、map、collect)
        List<String> collect2 = list.stream().sorted((s1, s2) -> (int) (s1.getScore() - s2.getScore())).map(Student::getName).collect(Collectors.toList());
        System.out.println(collect2);

        //需求4:根据姓氏的开头字母来排序(map、sorted、collect)
        List<String> collect3 = list.stream().map(Student::getName).sorted(Comparator.naturalOrder()).collect(Collectors.toList()); //Comparator.naturalOrder()返回的也是一个Comparator
        List<String> collect4 = list.stream().map(Student::getName).sorted((name1, name2) -> name1.length() - name2.length()).collect(Collectors.toList());
        List<String> collect5 = list.stream().sorted((student1, student2) -> student1.getName().compareTo(student2.getName())).map(Student::getName).collect(Collectors.toList());

        System.out.println(collect3);
        System.out.println(collect4);
        System.out.println(collect5);

        //需求5:查出成绩排名第二第三的学生姓名(sorted、skip、limit、map、collect)
        List<String> collect6 = list.stream().sorted((student1, student2) -> (int) (student1.getScore() - student2.getScore())).skip(1).limit(2).map(Student::getName).collect(Collectors.toList());
        System.out.println(collect6);

        //需求6:将id和姓名封装成键值对,方便查找(list ——> map)
//        Map<Integer, String> collect7 = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
//        System.out.println(collect7);
        //上述写法如果有重复的id,即key重复时,会直接抛错,我们也可以指定一下如果出现重复key,采用的策略
        Map<Integer, String> collect8 = list.stream().collect(Collectors.toMap(Student::getId, Student::getName, (preKey, nextKey) -> preKey));//保留先出现的key
        System.out.println(collect8);


    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student{
    private Integer id;

    private String name;

    private Integer age;

    private Long score;
}

 

上一篇:三 Prometheus 监控 Mysql


下一篇:Java8新特性-Lambda表达式与Stream API