JAVA 8 Stream的使用

2022-10-15  本文已影响0人  Nick_4438

例子代码1

package com.example.streamdemo;

import java.io.Console;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.*;

public class OperationStream {

    public static void filterTest() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = integerList.stream().filter(i -> i > 3);
        System.out.println("filterTest:" + stream.collect(toList()).toString());
    }

    public static void distinctTest() {
        List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = integerList.stream().distinct();
        System.out.println("distinctTest:" + stream.collect(toList()).toString());
    }

    public static void limitTest() {
        List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = integerList.stream().limit(3);
        System.out.println("limitTest:" + stream.collect(toList()).toString());
    }

    public static void skipTest() {
        List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = integerList.stream().skip(3);//跳过3个数
        System.out.println("skipTest:" + stream.collect(toList()).toString());
    }

    public static void mapTest() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        List<Integer> collect = stringList.stream()
                .map(String::length)
                .collect(toList());
        System.out.println("mapTest:" + collect.toString());
    }

    // 将一个流中的每个值都转换为另一个流.
    //    map(w -> w.split(" ")) 的返回值为 Stream<String[]>,
    //    想获取 Stream,可以通过flatMap方法完成 Stream ->Stream 的转换。
    public static void flatMapTest() {
        List<String> wordList = Arrays.asList("Java 8", "Lam bdas", "In", "Action");

        List<String> strList = wordList.stream()
                .map(w -> w.split(" "))
                .flatMap(Arrays::stream)
//                .distinct()
                .collect(toList());

        System.out.println("flatMapTest:" + strList.toString());
    }

    //allMatch 匹配所有元素
    public static void allMatchTest() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);

        if (integerList.stream().allMatch(i -> i > 3)) {
            System.out.println("allMatchTest:所有元素值都大于3");
        } else {
            System.out.println("allMatchTest:并非所有元素值都大于3");
        }
    }

    //anyMatch匹配其中一个
    public static void anyMatchTest() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);

        if (integerList.stream().anyMatch(i -> i > 3)) {
            System.out.println("anyMatchTest:存在值大于3的元素");
        } else {
            System.out.println("anyMatchTest:不存在值大于3的元素");
        }
    }

    //    noneMatch 全部不匹配
    public static void noneMatchTest() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        if (integerList.stream().noneMatch(i -> i > 3)) {
            System.out.println("值都小于3的元素");
        } else {
            System.out.println("值不都小于3的元素");
        }
    }

    public static void count() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Long result = integerList.stream().count();
        System.out.println("count:" + result);

    }

    //     findFirst 查找第一个
    public static void findFirst() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Optional<Integer> result = integerList.stream().filter(i -> i > 3).findFirst();
        System.out.println(result.orElse(-1));

    }

    public static void findAny() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Optional<Integer> result = integerList.stream().filter(i -> i > 3).findAny();
        System.out.println(result.orElse(-1));
    }

    //    reduce 将流中的元素组合
//    reduce接受两个参数,一个初始值这里是0,一个 BinaryOperatoraccumulator
//    来将两个元素结合起来产生一个新值,另外reduce方法还有一个没有初始化值的重载方法。
    public static void reduce() {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        int sum = integerList.stream()
                .reduce(0, Integer::sum);
    }

    public static void reduce1() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        Optional<Integer> min = stringList.stream()
                .map(String::length)
                .reduce(Integer::min);

        Optional<Integer> max = stringList.stream()
                .map(String::length)
                .reduce(Integer::max);

    }

    //    collect 返回集合
    public static void collectTest() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        List<Integer> intList = stringList.stream()
                .map(String::length)
                .collect(toList());
        System.out.println("collectTest:" + intList.toString());


        Set<Integer> intSet = stringList.stream()
                .map(String::length)
                .collect(toSet());
        System.out.println("collectTest:" + intSet.toString());

    }

    //joining 拼接流中的元素
    public static void joining() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        String result = stringList.stream()
                .map(String::toLowerCase)
                .collect(Collectors.joining(","));
        System.out.println("joining:" + result.toString());
    }

    //    groupingBy 分组
    public static void groupingBy1() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        Map<Integer, List<String>> collect = stringList.stream().collect(groupingBy(String::length));
        System.out.println("groupingBy1:" + collect.toString());
    }

    public static void groupingBy2() {
        List<String> stringList = Arrays.asList("Java 12", "Lambdas", "In", "Action");
        Map<Integer, Map<String, List<String>>> collect = stringList.stream()
                .collect(groupingBy(
                        String::length,
                        groupingBy(item -> {
                            if (item.length() <= 2) {
                                return "level1";
                            } else if (item.length() <= 6) {
                                return "level2";
                            } else {
                                return "level3";
                            }
                        })
                ));
        System.out.println("groupingBy2:" + collect.toString());
    }

    //    partitioningBy 分区
    public static void partitioningBy() {
//        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
//        Map<Boolean, List<Integer>> result = integerList.stream().collect(partitioningBy(i -> i < 3));

    }

    public static void sum1() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");
        int sum = stringList.stream()
//                .mapToInt(v->{
//                    return stringList.size();
//                })
                .mapToInt(String::length)
                .sum();
        System.out.println("sum1:" + sum);
    }

    public static void sum2() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");
        int sum = stringList.stream()
                .collect(summingInt(String::length));
        System.out.println("sum2:" + sum);
    }

    public static void sum3() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");
        int sum = stringList.stream()
                .map(String::length)
                .reduce(0, Integer::sum);
        System.out.println("sum3:" + sum);
    }

    public static void average1() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        double average = stringList.stream()
                .collect(averagingInt(String::length));

        System.out.println("average1:" + average);
    }

    //    summarizingxxx 同时求总和、平均值、最大值、最小值
//    如果数据类型为double、long,则通过summarizingDouble、summarizingLong方法
    public static void summarizingxxx() {
        List<String> stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");

        IntSummaryStatistics intSummaryStatistics = stringList.stream()
                .collect(summarizingInt(String::length));

        double average = intSummaryStatistics.getAverage(); // 获取平均值
        int min = intSummaryStatistics.getMin();            // 获取最小值
        int max = intSummaryStatistics.getMax();            // 获取最大值
        long sum = intSummaryStatistics.getSum();           // 获取总和
        System.out.println("summarizingxxx:" + min);
        System.out.println("summarizingxxx:" + max);
        System.out.println("summarizingxxx:" + average);
        System.out.println("summarizingxxx:" + sum);
    }


    public static void main(String[] args) {
        filterTest();
        distinctTest();
        limitTest();
        skipTest();
        mapTest();
        flatMapTest();
        allMatchTest();
        anyMatchTest();
        count();
        average1();
        sum1();
        sum2();
        sum3();
        summarizingxxx();
        findFirst();
        findAny();
        reduce();
        reduce1();
        collectTest();
        joining();
        groupingBy1();
        groupingBy2();
        partitioningBy();
    }
}

例子代码2

package com.example.streamdemo;

public class Student {
    private String name;//姓名
    private Integer age;//年龄
    private int sex;//性别
    private String professional;//专业
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String getProfessional() {
        return professional;
    }
    public void setProfessional(String professional) {
        this.professional = professional;
    }
    public Student(String name, Integer age, int sex, String professional) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.professional = professional;
    }
}



package com.example.streamdemo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class GroupByMain {
    public static void main(String[] args) {
        List<Student> allList = new ArrayList<Student>();
        Student st1 = new Student("小王",26,1,"计算机");
        allList.add(st1);
        Student st2 = new Student("小张",21,1,"电气");
        allList.add(st2);
        Student st3 = new Student("小红",22,1,"人文");
        allList.add(st3);
        Student st4 = new Student("小李",23,1,"计算机");
        allList.add(st4);

        // 以专业分组
        Map<String, List<Student>> MapStudent = allList.stream().collect(
                Collectors.groupingBy(Student::getProfessional));
        for (Map.Entry<String, List<Student>> entry: MapStudent.entrySet()) { // 遍历获取对象信息
            List<Student> student = entry.getValue();
            System.out.println(student.toString());
        }
        System.out.println("------------分割线---------------");
        // 以专业分组,并选取年龄最大的 学生
        Map<String, Optional<Student>> MapStudent1 = allList.stream().collect(
                Collectors.groupingBy(Student::getProfessional, Collectors.maxBy((o1, o2) -> o1.getAge().compareTo(o2.getAge()))));
        // 遍历获取对象信息
        for (Map.Entry<String, Optional<Student>> entry: MapStudent1.entrySet()) {
            Student student = entry.getValue().get();
            System.out.println(entry.getKey()+":"+student.getName().toString());
        }

        //        分组求和
        System.out.println("------------分组年龄求和---------------");
        for (Map.Entry<String, List<Student>> entry: MapStudent.entrySet()) { // 遍历获取对象信息
            List<Student> student = entry.getValue();
            System.out.println(entry.getKey()+":"+ student.stream().mapToInt(v-> v.getAge()).sum());
        }
        //        分组求和
        System.out.println("------------分组年龄求最大值---------------");
        for (Map.Entry<String, List<Student>> entry: MapStudent.entrySet()) { // 遍历获取对象信息
            List<Student> student = entry.getValue();
            System.out.println(entry.getKey()+":"+ student.stream().mapToInt(v-> v.getAge()).max());
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读