Guava Predicate 用法整理

原文: http://www.javarticles.com/2015/04/guava-predicate-examples.html
最近工作用 因为用的jdk是1.7, 所以函数式主要用guava的一些工具类, 如果是jdk8 各种流式编程,各种节省代码。不过以后要跟着大神们向java9看齐了

dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javarticles.guava</groupId>
    <artifactId>guavaEventBusExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
    </dependencies>
</project>

Predicate Filter Example

package com.javarticles.guava;

public class Movie {
    private String name;
    private Genre genre;
    private double rating;

    Movie(String name, Genre genre, double rating) {
        this.name = name;
        this.genre = genre;
        this.rating = rating;
    }

    public String toString() {
        return name + "(" + genre + ", " + rating + ")";
    }

    public String getName() {
        return name;
    }

    public Genre getGenre() {
        return genre;
    }

    public double getRating() {
        return rating;
    }

}
package com.javarticles.guava;

public enum Genre {
    DRAMA, THRILLER, HORROR, ROMANTIC, ACTION
}

FilterByGenre:

package com.javarticles.guava;

import com.google.common.base.Predicate;

public enum FilterByGenre implements Predicate {
    DRAMA(Genre.DRAMA), 
    THRILLER(Genre.THRILLER), 
    ROMANTIC(Genre.ROMANTIC), 
    ACTION(Genre.ACTION), 
    HORROR(Genre.HORROR);

    FilterByGenre(Genre genre) {
        this.genre = genre;
    }

    public boolean apply(Movie movie) {
        return movie.getGenre() == genre;
    }

    private Genre genre;
}

FilterByRating:

package com.javarticles.guava;

import com.google.common.base.Predicate;

public class FilterByRating implements Predicate {
    public static final FilterByRating _8 = new FilterByRating(8);
    private double grade;
    FilterByRating(double grade) {
        this.grade = grade;
    }
    public boolean apply(Movie movie) {
        return movie.getRating() > grade;
    }
}

PrintMovie:

package com.javarticles.guava;

import java.util.function.Consumer;

public class PrintMovie implements Consumer {
    public void accept(Movie movie) {
        System.out.println(movie);
    }        
}

Now let’s start with our first example which is to determine whether on applying the predicate, all the movies return true.
Our predicate determines whether the movies passed in have rating above 8.

PredicateExample:

package com.javarticles.guava;

import java.util.Arrays;
import java.util.List;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;

public class PredicateExample {
    private static final PrintMovie PRINT_MOVIE = new PrintMovie();

    public static void main(String[] args) {
        Movie[] movies = new Movie[] { m("Green Mile", Genre.DRAMA, 8.5),
                m("Forrest Gump", Genre.DRAMA, 8.8),
                m("A Beautiful Mind", Genre.DRAMA, 8.2),
                m("The Notebook", Genre.ROMANTIC, 7.9),
                m("The Titanic", Genre.ROMANTIC, 7.7),
                m("Pretty Woman", Genre.ROMANTIC, 6.9),
                m("Notting Hill", Genre.ROMANTIC, 7),
                m("Inception", Genre.THRILLER, 8.8),
                m("The Game", Genre.THRILLER, 7.8),
                m("Seven", Genre.THRILLER, 8.7),
                m("The Dark Knight", Genre.THRILLER, 9),
                m("The Exorcist", Genre.HORROR, 8),
                m("The Shinning", Genre.HORROR, 8.5),
                m("The Cabin in the Woods", Genre.HORROR, 7),
                m("Insidious", Genre.HORROR, 6.8),
                m("The Avengers", Genre.ACTION, 8.2),
                m("Die Hard", Genre.ACTION, 8.3),
                m("Casino Royale", Genre.ACTION, 8),
                m("Star Wars", Genre.ACTION, 8.7), m("Thor", Genre.ACTION, 7) };
        List<Movie> movieList = Arrays.asList(movies);

        // Are these movies rated above 8?
        boolean ratedAbove8 = Iterables.all(
                Arrays.asList(movies[0], movies[1], movies[2]),
                FilterByRating._8);
        System.out.println("Are these movies " + movies[0] + ", " + movies[1]
                + ", " + movies[2] + " rated above 8? " + ratedAbove8);
        System.out
                .println("-----------------------------------------------------------------");
    }

    private static Movie m(String name, Genre genre, double rating) {
        return new Movie(name, genre, rating);
    }
}

Output:

Are these movies Green Mile(DRAMA, 8.5), Forrest Gump(DRAMA, 8.8), A Beautiful Mind(DRAMA, 8.2) rated above 8? true

Filter using predicate

PredicateExample:

package com.javarticles.guava;

import java.util.Arrays;
import java.util.List;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;

public class PredicateExample {
    private static final PrintMovie PRINT_MOVIE = new PrintMovie();

    public static void main(String[] args) {
        Movie[] movies = new Movie[] { m("Green Mile", Genre.DRAMA, 8.5),
                m("Forrest Gump", Genre.DRAMA, 8.8),
                m("A Beautiful Mind", Genre.DRAMA, 8.2),
                m("The Notebook", Genre.ROMANTIC, 7.9),
                m("The Titanic", Genre.ROMANTIC, 7.7),
                m("Pretty Woman", Genre.ROMANTIC, 6.9),
                m("Notting Hill", Genre.ROMANTIC, 7),
                m("Inception", Genre.THRILLER, 8.8),
                m("The Game", Genre.THRILLER, 7.8),
                m("Seven", Genre.THRILLER, 8.7),
                m("The Dark Knight", Genre.THRILLER, 9),
                m("The Exorcist", Genre.HORROR, 8),
                m("The Shinning", Genre.HORROR, 8.5),
                m("The Cabin in the Woods", Genre.HORROR, 7),
                m("Insidious", Genre.HORROR, 6.8),
                m("The Avengers", Genre.ACTION, 8.2),
                m("Die Hard", Genre.ACTION, 8.3),
                m("Casino Royale", Genre.ACTION, 8),
                m("Star Wars", Genre.ACTION, 8.7), m("Thor", Genre.ACTION, 7) };
        List<Movie> movieList = Arrays.asList(movies);

        // Are these movies rated above 8?
        boolean ratedAbove8 = Iterables.all(
                Arrays.asList(movies[0], movies[1], movies[2]),
                FilterByRating._8);
        System.out.println("Are these movies " + movies[0] + ", " + movies[1]
                + ", " + movies[2] + " rated above 8? " + ratedAbove8);
        System.out
                .println("-----------------------------------------------------------------");

        // Filter by Thriller Genre
        System.out.println("Filter thriller genre from the movies list>>");
        Iterable<Movie> thrillers = Iterables.filter(movieList,
                FilterByGenre.THRILLER);
        thrillers.forEach(PRINT_MOVIE);
        System.out
                .println("-----------------------------------------------------------------");
    }

    private static Movie m(String name, Genre genre, double rating) {
        return new Movie(name, genre, rating);
    }
}

Output:

Are these movies Green Mile(DRAMA, 8.5), Forrest Gump(DRAMA, 8.8), A Beautiful Mind(DRAMA, 8.2) rated above 8? true
-----------------------------------------------------------------
Filter thriller genre from the movies list>>
Inception(THRILLER, 8.8)
The Game(THRILLER, 7.8)
Seven(THRILLER, 8.7)
The Dark Knight(THRILLER, 9.0)
-----------------------------------------------------------------

Compose two predicates using ‘and’

package com.javarticles.guava;

import java.util.Arrays;
import java.util.List;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;

public class PredicateExample {
    private static final PrintMovie PRINT_MOVIE = new PrintMovie();

    public static void main(String[] args) {
        Movie[] movies = new Movie[] { m("Green Mile", Genre.DRAMA, 8.5),
                m("Forrest Gump", Genre.DRAMA, 8.8),
                m("A Beautiful Mind", Genre.DRAMA, 8.2),
                m("The Notebook", Genre.ROMANTIC, 7.9),
                m("The Titanic", Genre.ROMANTIC, 7.7),
                m("Pretty Woman", Genre.ROMANTIC, 6.9),
                m("Notting Hill", Genre.ROMANTIC, 7),
                m("Inception", Genre.THRILLER, 8.8),
                m("The Game", Genre.THRILLER, 7.8),
                m("Seven", Genre.THRILLER, 8.7),
                m("The Dark Knight", Genre.THRILLER, 9),
                m("The Exorcist", Genre.HORROR, 8),
                m("The Shinning", Genre.HORROR, 8.5),
                m("The Cabin in the Woods", Genre.HORROR, 7),
                m("Insidious", Genre.HORROR, 6.8),
                m("The Avengers", Genre.ACTION, 8.2),
                m("Die Hard", Genre.ACTION, 8.3),
                m("Casino Royale", Genre.ACTION, 8),
                m("Star Wars", Genre.ACTION, 8.7), m("Thor", Genre.ACTION, 7) };
        List<Movie> movieList = Arrays.asList(movies);

        // Are these movies rated above 8?
        boolean ratedAbove8 = Iterables.all(
                Arrays.asList(movies[0], movies[1], movies[2]),
                FilterByRating._8);
        System.out.println("Are these movies " + movies[0] + ", " + movies[1]
                + ", " + movies[2] + " rated above 8? " + ratedAbove8);
        System.out
                .println("-----------------------------------------------------------------");

        // Filter by Thriller Genre
        System.out.println("Filter thriller genre from the movies list>>");
        Iterable<Movie> thrillers = Iterables.filter(movieList,
                FilterByGenre.THRILLER);
        thrillers.forEach(PRINT_MOVIE);
        System.out
                .println("-----------------------------------------------------------------");

        System.out.println("Filter action movies rated above 8>>");
        Predicate<Movie> actionAbove8Rating = Predicates.and(
                FilterByGenre.ACTION, FilterByRating._8);
        Iterable<Movie> actionMoviesAbove8 = Iterables.filter(movieList,
                actionAbove8Rating);
        actionMoviesAbove8.forEach(PRINT_MOVIE);
    }

    private static Movie m(String name, Genre genre, double rating) {
        return new Movie(name, genre, rating);
    }
}

Output:

Are these movies Green Mile(DRAMA, 8.5), Forrest Gump(DRAMA, 8.8), A Beautiful Mind(DRAMA, 8.2) rated above 8? true
-----------------------------------------------------------------
Filter thriller genre from the movies list>>
Inception(THRILLER, 8.8)
The Game(THRILLER, 7.8)
Seven(THRILLER, 8.7)
The Dark Knight(THRILLER, 9.0)
-----------------------------------------------------------------
Filter action movies rated bove 8>>
The Avengers(ACTION, 8.2)
Die Hard(ACTION, 8.3)
Star Wars(ACTION, 8.7)
posted @ 2017-09-04 23:44  cbam  阅读(185)  评论(0编辑  收藏  举报