zoukankan      html  css  js  c++  java
  • 一个例子理解Predicate、Consumer和Stream

    一个需求:

    把年龄大于20的学生的信息打印出来。

    面向对象编程

    public class Student {
    
        private String name;
        
        private int age;
        
        private int number;
        
        public Student(String name,int age,int number){
            this.name = name;
            this.age = age;
            this.number = number;
        }
        
        public String toString(){    
            return "name:"+name+" "+"age:"+age+" "+"number:"+number;
        }
    
        public int getAge() {
            return age;
        }
        //省略其他get set方法
    
    }
     1 public class Test {
     2 
     3     public static void main(String[] args) {
     4         Student student1 = new Student("ouym",21,1000);
     5         if(student1.getAge()>20){
     6             System.out.println(student1.toString());
     7         }
     8     }
     9     
    10 }

    如果Test类中line5~7在多处使用,我们还可以将其封装成函数。在Student类中添加函数

    public void printIfGTParam(Student student,int age){
            if(student.getAge()>age){
                System.out.println(student.toString());
            }
        }

    Test改为如下:

    public class Test {
    
        public static void main(String[] args) {
            Student student1 = new Student("ouym",21,1000);
            student1.printIfGTParam(student1, 20);
        }    
    }

    但是如果需求变了呢?现在我们需要把名字为ouym的学生信息打印出来。

    两个方案:(1)修改printIfGTParam函数,加几个判定条件。但是这明显不符合开闭原则。

    (2)添加一个新的函数,处理该需求。如果又有新的需求的话,一直添加代码显得不干净。

    下面介绍一个更合理的方法,函数编程。

    函数编程

    import java.util.function.Consumer;
    import java.util.function.Predicate;
    
    public class Student {
    
        private String name;
        
        private int age;
        
        private int number;
        
        public Student(String name,int age,int number){
            this.name = name;
            this.age = age;
            this.number = number;
        }
        
        public String toString(){    
            return "name:"+name+" "+"age:"+age+" "+"number:"+number;
        }
        
        public void printIf(Predicate<Student> predicate, 
                Consumer<Student> consumer){
            if ( predicate.test(this)){
                consumer.accept(this);
            }
        }
    
        public int getAge() {
            return age;
        }
       //省略其他set、get方法
    
    }
    public class Test {
    
        public static void main(String[] args) {
            Student student1 = new Student("ouym",21,1000);
            student1.printIf(student -> student.getAge()>20, 
                    student -> System.out.println(student.toString()));    
        }
        
    }

    如果需求改为打印姓名为ouym的学生信息的时候,我们只需要在调用printIf方法的时候把student -> student.getAge()>20改为student -> student.getName()=="ouym"即可。好处不言而喻。这里只是处理一个学生,如果要处理多个学生呢?一个简单的方法是使用for循环,Student类不变,将Test改为如下:

    public class Test {
    
        public static void main(String[] args) {
            Student student1 = new Student("ouym1",19,1000);
            Student student2 = new Student("ouym2",20,1001);
            Student student3 = new Student("ouym3",21,1002);
            Student student4 = new Student("ouym4",22,1003);
            
            List<Student> students = new ArrayList<>();
            students.add(student1);
            students.add(student2);
            students.add(student3);
            students.add(student4);
            
            for(Student one : students){
                one.printIf(student -> student.getAge()>20, 
                        student -> System.out.println(student.toString()));    
            }    
        }
            
    }

    对于集合的情况,Java8的函数编程也提供了stream接口支持。

    public class Test {
    
        public static void main(String[] args) {
            Student student1 = new Student("ouym1",19,1000);
            Student student2 = new Student("ouym2",20,1001);
            Student student3 = new Student("ouym3",21,1002);
            Student student4 = new Student("ouym4",22,1003);
            
            List<Student> students = new ArrayList<>();
            students.add(student1);
            students.add(student2);
            students.add(student3);
            students.add(student4);
            
            students.stream().filter(student -> student.getAge()>20)
            .forEach(student -> System.out.println(student.toString()));
            
        }    
    }

    这里只是stream一个简单的操作,更多详情介绍请看总结部分。

     总结

    (1)Predicate

    Represents a predicate (boolean-valued function) of one argument.

    表示一个参数的谓词(布尔值函数)。源码如下(函数接口都有@FunctionalInterface注解修饰):

    @FunctionalInterface
    public interface Predicate<T> {
    
        boolean test(T t);
    
       //提供的Predicate和本身的Predicate都为true,返回的Predicate才是true
        default Predicate<T> and(Predicate<? super T> other) {
            Objects.requireNonNull(other);
            return (t) -> test(t) && other.test(t);
        }
    
       //同理,非操作
        default Predicate<T> negate() {
            return (t) -> !test(t);
        }
    
       //同理,或
        default Predicate<T> or(Predicate<? super T> other) {
            Objects.requireNonNull(other);
            return (t) -> test(t) || other.test(t);
        }
    
       
        static <T> Predicate<T> isEqual(Object targetRef) {
            return (null == targetRef)
                    ? Objects::isNull
                    : object -> targetRef.equals(object);
        }
    }

    所以Predicate的主要作用是调用test方法评估一个对象,评估方法是在调用的时候以函数作为参数传递进去,评估结果以boolean类型返回。具体看上述例子。

    (2)Consumer接口

    Represents an operation that accepts a single input argument and returns no result. 
    Unlike most other functional interfaces, {@code Consumer} is expected to operate via side-effects.

    即接口表示一个接受单个输入参数并且没有返回值的操作。不像其他函数式接口,Consumer接口期望执行带有副作用的操作(Consumer的操作可能会更改输入参数的内部状态)。

    @FunctionalInterface
    public interface Consumer<T> {
    
        void accept(T t);
    
        default Consumer<T> andThen(Consumer<? super T> after) {
            Objects.requireNonNull(after);
            return (T t) -> { accept(t); after.accept(t); };
        }

    accept方法接收一个对象,具体的操作在调用的时候以函数作为参数传递进去,没有返回值。

    andThen方法是个defaul方法,表示先执行本身的 accept方法,紧接着再执行afteraccept方法。

    (3)Stream(来自

    Stream 是用函数式编程方式在集合类上进行复杂操作的工具,其集成了Java 8中的众多新特性之一的聚合操作。

    对聚合操作的使用(创建流后)可以归结为2个部分:

    • Intermediate:一个流可以后面跟随零个或多个 intermediate 操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历。
    • Terminal:一个流只能有一个 terminal 操作,当这个操作执行后,流就被使用“光”了,无法再被操作。所以这必定是流的最后一个操作。Terminal 操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个 side effect。

    还有一种操作被称为 short-circuiting。用以指:

    • 对于一个 intermediate 操作,如果它接受的是一个无限大(infinite/unbounded)的 Stream,但返回一个有限的新 Stream。
    • 对于一个 terminal 操作,如果它接受的是一个无限大的 Stream,但能在有限的时间计算出结果。

    当操作一个无限大的 Stream,而又希望在有限时间内完成操作,则在管道内拥有一个 short-circuiting 操作是必要非充分条件。

    构造流的几种常见方法:
    // 1. Individual values
    Stream stream = Stream.of("a", "b", "c");
    // 2. Arrays
    String [] strArray = new String[] {"a", "b", "c"};
    stream = Stream.of(strArray);
    stream = Arrays.stream(strArray);
    // 3. Collections
    List<String> list = Arrays.asList(strArray);
    stream = list.stream();

    对于基本数值型,目前有三种对应的包装类型 Stream:

    IntStream、LongStream、DoubleStream。当然我们也可以用 Stream<Integer>、Stream<Long> >、Stream<Double>,但是 boxing 和 unboxing 会很耗时,所以特别为这三种基本数值型提供了对应的 Stream。

    流转换为其它数据结构:
    // 1. Array
    String[] strArray1 = stream.toArray(String[]::new);
    // 2. Collection
    List<String> list1 = stream.collect(Collectors.toList());
    List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
    Set set1 = stream.collect(Collectors.toSet());
    Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
    // 3. String
    String str = stream.collect(Collectors.joining()).toString();

    一个 Stream 只可以使用一次。

    stream的操作:

    Intermediate:
    
    map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
    
    Terminal:
    
    forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
    
    Short-circuiting:
    
    anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit

    下面看一下 Stream 的比较典型用法:

    map/flatMap

    它的作用就是把 input Stream 的每一个元素,映射成 output Stream 的另外一个元素。

    //转换大写
    List<String> output = wordList.stream().
    map(String::toUpperCase).
    collect(Collectors.toList());
    
    //平方数
    List<Integer> nums = Arrays.asList(1, 2, 3, 4);
    List<Integer> squareNums = nums.stream().
    map(n -> n * n).
    collect(Collectors.toList());
    
    //一对多flatMap 把 input Stream 中的层级结构扁平化,就是将最底层元素抽出来放到一起,
    //最终 output 的新 Stream 里面已经没有 List 了,都是直接的数字。
    Stream<List<Integer>> inputStream = Stream.of( Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6) ); Stream<Integer> outputStream = inputStream. flatMap((childList) -> childList.stream());

    filter

    filter 对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream。

    //留下偶数
    Integer[] sixNums = {1, 2, 3, 4, 5, 6};
    Integer[] evens =
    Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
    
    //首先把每行的单词用 flatMap 整理到新的 Stream,然后保留长度不为 0 的,
    //就是整篇文章中的全部单词了。
    List<String> output = reader.lines().
     flatMap(line -> Stream.of(line.split(REGEXP))).
     filter(word -> word.length() > 0).
     collect(Collectors.toList());

    forEach

    forEach 方法接收一个 Lambda 表达式,然后在 Stream 的每一个元素上执行该表达式。

    //打印姓名
    // 1、stream
    roster.stream()
     .filter(p -> p.getGender() == Person.Sex.MALE)
     .forEach(p -> System.out.println(p.getName()));
    // 2、for循环
    for (Person p : roster) {
     if (p.getGender() == Person.Sex.MALE) {
     System.out.println(p.getName());
     }
    }

    一般认为,forEach 和常规 for 循环的差异不涉及到性能,它们仅仅是函数式风格与传统 Java 风格的差别。

    另外一点需要注意,forEach 是 terminal 操作,因此它执行后,Stream 的元素就被“消费”掉了,你无法对一个 Stream 进行两次 terminal 运算。

    还有一个具有相似功能的 intermediate 操作 peek 可以达到上述目的。(可以多次调用)

    Stream.of("one", "two", "three", "four")
     .filter(e -> e.length() > 3)
     .peek(e -> System.out.println("Filtered value: " + e))
     .map(String::toUpperCase)
     .peek(e -> System.out.println("Mapped value: " + e))
     .collect(Collectors.toList());

    reduce

    这个方法的主要作用是把 Stream 元素组合起来。它提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面 Stream 的第一个、第二个、第 n 个元素组合。从这个意义上说,字符串拼接、数值的 sum、min、max、average 都是特殊的 reduce。

    // 字符串连接,concat = "ABCD"
    String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat); 
    // 求最小值,minValue = -3.0
    double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min); 
    // 求和,sumValue = 10, 有起始值
    int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
    // 求和,sumValue = 10, 无起始值
    sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
    // 过滤,字符串连接,concat = "ace"
    concat = Stream.of("a", "B", "c", "D", "e", "F").
     filter(x -> x.compareTo("Z") > 0).
     reduce("", String::concat);

    上面代码例如第一个示例的 reduce(),第一个参数(空白字符)即为起始值,第二个参数(String::concat)为 BinaryOperator。这类有起始值的 reduce() 都返回具体的对象。而对于第四个示例没有起始值的 reduce(),由于可能没有足够的元素,返回的是 Optional,需要通过Optional的get方法获取对象,请留意这个区别。

    Optional是Java8提供的为了解决null安全问题的一个API。

    //一般写法
    public static String getName(User u) {
        if (u == null)
            return "Unknown";
        return u.name;
    }
    
    //使用Optional
    public static String getName(User u) {
        return Optional.ofNullable(u)
                        .map(user->user.name)
                        .orElse("Unknown");
    }

    关于Optional的更多详情请自行查阅api

    limit/skip

    limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素。

    public void testLimitAndSkip() {
            List<Person> persons = new ArrayList();
            for (int i = 1; i <= 10000; i++) {
                Person person = new Person(i, "name" + i);
                persons.add(person);
            }
            List<String> personList2 = persons.stream().map(Person::getName).limit(10).skip(3).collect(Collectors.toList());
            System.out.println(personList2);
        }
    
        private class Person {
            public int no;
            private String name;
    
            public Person(int no, String name) {
                this.no = no;
                this.name = name;
            }
    
            public String getName() {
                System.out.println(name);
                return name;
            }
        }

    输出结果为:

    name1
    name2
    name3
    name4
    name5
    name6
    name7
    name8
    name9
    name10
    [name4, name5, name6, name7, name8, name9, name10]

    这是一个有 10,000 个元素的 Stream,但在 short-circuiting 操作 limit 和 skip 的作用下,管道中 map 操作指定的 getName() 方法的执行次数为 limit 所限定的 10 次,而最终返回结果在跳过前 3 个元素后只有后面 7 个返回。

    sorted

    对 Stream 的排序通过 sorted 进行,它比数组的排序更强之处在于你可以首先对 Stream 进行各类 map、filter、limit、skip 甚至 distinct 来减少元素数量后,再排序,这能帮助程序明显缩短执行时间。

    List<Person> persons = new ArrayList();
            for (int i = 1; i <= 5; i++) {
                Person person = new Person(i, "name" + i);
                persons.add(person);
            }
            List<Person> personList2 = persons.stream().limit(2).sorted((p1, p2) -> p1.getName().compareTo(p2.getName()))
                    .collect(Collectors.toList());
            System.out.println(personList2);

    Match

    Stream 有三个 match 方法,从语义上说:

    • allMatch:Stream 中全部元素符合传入的 predicate,返回 true
    • anyMatch:Stream 中只要有一个元素符合传入的 predicate,返回 true
    • noneMatch:Stream 中没有一个元素符合传入的 predicate,返回 true

    它们都不是要遍历全部元素才能返回结果。例如 allMatch 只要一个元素不满足条件,就 skip 剩下的所有元素,返回 false。

    对之前的 Person 类稍做修改,加入一个 age 属性和 getAge 方法。

    List<Person> persons = new ArrayList();
    persons.add(new Person(1, "name" + 1, 10));
    persons.add(new Person(2, "name" + 2, 21));
    persons.add(new Person(3, "name" + 3, 34));
    persons.add(new Person(4, "name" + 4, 6));
    persons.add(new Person(5, "name" + 5, 55));
    boolean isAllAdult = persons.stream().
     allMatch(p -> p.getAge() > 18);
    System.out.println("All are adult? " + isAllAdult);

    min/max/distinct

    //找出最长一行的长度
    BufferedReader br = new BufferedReader(new FileReader("c:\SUService.log"));
    int longest = br.lines().
     mapToInt(String::length).
     max().
     getAsInt();
    br.close();
    System.out.println(longest);
    
    //找出不重复的单词,转小写,并排序
    List<String> words = br.lines().
     flatMap(line -> Stream.of(line.split(" "))).
     filter(word -> word.length() > 0).
     map(String::toLowerCase).
     distinct().
     sorted().
     collect(Collectors.toList());
    br.close();
    System.out.println(words);

  • 相关阅读:
    【BZOJ 3309】DZY Loves Math
    【51Nod 1239】欧拉函数之和
    【51Nod 1244】莫比乌斯函数之和
    莫比乌斯反演与杜教筛
    【BZOJ 3993】【SDOI 2015】星际战争
    【BZOJ 3876】【AHOI 2014】支线剧情
    【hihoCoder 1454】【hiho挑战赛25】【坑】Rikka with Tree II
    【BZOJ 1061】【Vijos 1825】【NOI 2008】志愿者招募
    【BZOJ 1016】【JSOI 2008】最小生成树计数
    【BZOJ 1005】【HNOI 2008】明明的烦恼
  • 原文地址:https://www.cnblogs.com/ouym/p/8926854.html
Copyright © 2011-2022 走看看