java 8 谓词_Java谓词– Java 8谓词

本文详细介绍了Java 8中的Predicate功能接口,它用于创建接受一个值并返回布尔结果的函数。通过示例展示了如何在lambda表达式中使用Predicate进行过滤操作,以及介绍了一些重要的Predicate方法,如and、or、negate和test。
摘要由CSDN通过智能技术生成

java 8 谓词

In this article, we’ll talk about Java Predicate, which is a Functional Interface. A Functional Interface is one that contains exactly one abstract method.

在本文中,我们将讨论Java谓词,它是一个功能接口 。 功能接口是仅包含一种抽象方法的接口。

Java谓词 (Java Predicate)

java predicate, java 8 predicate

Remember predicate from Math class in school? Yeah, something like a function that takes in a value and returns true or false.


还记得学校数学课上的谓词吗? 是的,类似于一个函数,该函数接受一个值并返回true或false。

In Java 8, java.util.function.Predicate was introduced that behaves the same way and can be used as an assignment target in lambda expressions and functional interfaces. The functional method of Predicate is test(Object).

在Java 8 java.util.function.Predicate ,引入了java.util.function.Predicate ,其行为方式相同,可用作lambda表达式和函数接口中的赋值目标。 Predicate的功能方法是test(Object)

Java谓词示例 (Java Predicate Example)

Let’s consider that we have a class Apple:

考虑一下我们有一个Apple类:

package com.journaldev.predicates;

public class Apple {
	private String color;
	private Double weight;

	public Apple(String c, Double w) {
		this.color = c;
		this.weight = w;
	}

	@Override
	public String toString() {
		return "Apple{color:" + this.getColor() + ",weight:" + this.getWeight() + "}";
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public Double getWeight() {
		return weight;
	}

	public void setWeight(Double weight) {
		this.weight = weight;
	}
}

Now if we have a condition to get the apples whose weight is above 150 grams, we can write a Predicate for it as below:

现在,如果我们有条件获取重量超过150克的苹果,则可以为其编写谓词,如下所示:

package com.journaldev.predicates;

import java.util.function.Predicate;

public class ApplePredicates {

	public static Predicate<Apple> isWeightAbove150() {
		return apple -> apple.getWeight() >= 150;
	}
}

Now, we can use this predicate in filter(), to filter a list of apples by the condition in this predicate.

现在,我们可以在filter ()使用此谓词,以根据该谓词中的条件来过滤苹果列表。

Let’s add a method filterApples() to the ApplePredicates class:

让我们向ApplePredicates类添加一个方法filterApples()

public static List<Apple> filterApples(List<Apple> apples, Predicate<Apple> predicate) {
	return apples.stream().filter(predicate).collect(Collectors.toList());
}

We can call this and get the results as below in a main method:

我们可以调用它,并在main方法中获得如下结果:

public static void main(String[] args) {
	List<Apple> apples = Arrays.asList(new Apple("green", 120.0), new Apple("red", 110.0),
			new Apple("brown", 150.0), new Apple("green", 160.0), new Apple("red", 122.0));
	ApplePredicates.filterApples(apples, ApplePredicates.isWeightAbove150()).forEach(System.out::println);
}

Output:

输出:

Apple{color:brown,weight:150.0}
Apple{color:green,weight:160.0}

With java 8 lambda expressions, we can do it simply as below:

使用Java 8 Lambda表达式,我们可以简单地做到如下:

ApplePredicates.filterApples(apples, apple -> {
	return apple.getWeight() >= 150;
}).forEach(System.out::println);

Or, if we don’t want to define our own method, we can also use the default filter method and write it as:

或者,如果我们不想定义自己的方法,也可以使用默认的filter方法并将其编写为:

apples.stream().filter(apple -> {
	return apple.getWeight() >= 150;
}).collect(Collectors.toList()).forEach(System.out::println);

Java 8谓词方法 (Java 8 Predicate Methods)

Let’s now go through the methods available for Predicate:

现在让我们看一下Predicate可用的方法:

  1. default Predicate and(Predicate other) (default Predicate and(Predicate other))

    Returns a composed predicate that represents a logical AND of two predicates. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

    To understand this, let’s add another predicate in the ApplePredicates class:

    public static Predicate<Apple> isColorGreen() {
        return apple -> apple.getColor().equals("green");
    }

    Now we can apply the and() function if we want to get a predicate for apple to be green and weight above or equal to 150 grams.

    This will give the following output:

    Apple{color:green,weight:160.0}

    Similarly, we have or() method to do the short-circuiting, logical ORing of two predicates.

    返回表示两个谓词的逻辑与的组合谓词。 在评估组合谓词时,如果该谓词为假,则不会评估另一个谓词。

    为了理解这一点,让我们在ApplePredicates类中添加另一个谓词:

    现在and()如果我们要使苹果成为绿色且重量大于或等于150克的谓词,则可以应用and()函数。

    Predicate<Apple> andPredicate = ApplePredicates.isColorGreen().and(ApplePredicates.isWeightAbove150());
    apples.stream().filter(andPredicate).forEach(System.out::println);

    这将给出以下输出:

    同样,我们有or()方法对两个谓词进行短路,逻辑或运算。

  2. default Predicate negate() (default Predicate negate())

    Returns a predicate that represents the logical negation of this predicate.

    Let’s say we want the Predicate to get apples that are not green. We already have one predicate that checks for Apple to be green, so we can negate it.

    Predicate<Apple> negateExample = ApplePredicates.isColorGreen().negate();
    apples.stream().filter(negateExample).forEach(System.out::println);

    The output will be:

    返回表示此谓词逻辑否定的谓词。

    假设我们希望谓词获得不是绿色的苹果。 我们已经有一个判断苹果是否为绿色的谓词,因此我们可以否定它。

    Predicate<Apple> negateExample = ApplePredicates.isColorGreen().negate();
    apples.stream().filter(negateExample).forEach(System.out::println);

    输出将是:

  3. boolean test(T t) (boolean test(T t))

    Evaluates this predicate for the given argument. In our case, we can pass in an Apple object to check if this predicate returns true or false for that apple.

    Apple testApple = new Apple("green", 120.0);
    System.out.println(ApplePredicates.isColorGreen().test(testApple));
    System.out.println(ApplePredicates.isWeightAbove150().test(testApple));

    Output:

    评估给定参数的谓词。 在我们的例子中,我们可以传入一个Apple对象,以检查该谓词对于该苹果返回的是true还是false。

    Apple testApple = new Apple("green", 120.0);
    System.out.println(ApplePredicates.isColorGreen().test(testApple));
    System.out.println(ApplePredicates.isWeightAbove150().test(testApple));

    输出:

  4. static Predicate isEqual(Object targetRef) (static Predicate isEqual(Object targetRef))

    Returns a predicate that tests if two arguments are equal according to Objects.equals() method.

    Consider we have overridden the equals() method for Apple class:

    @Override
    public boolean equals(Object obj) {
    	Apple apple = (Apple) obj;
    	if (this.getColor().equals(apple.getColor()) && this.getWeight().equals(apple.getWeight())) {
    		return true;
    	}
    	return false;
    }

    Now, let’s say we have an Apple, which has standard color and weight. Then we can get a Predicate, that will test if the given apple is standard or not.

    This will output:

    false
    true

    返回一个谓词,该谓词根据Objects.equals()方法测试两个参数是否相等。

    考虑我们已经为Apple类重写了equals()方法:

    现在,假设我们有一个具有标准颜色和重量的苹果。 然后我们可以获得一个谓词,它将测试给定的苹果是否为标准苹果。

    Predicate<Apple> standardApplePredicate = Predicate.isEqual(new Apple("red", 150.0));
    
    Apple testApple = new Apple("green", 120.0);
    System.out.println(standardApplePredicate.test(testApple));
    System.out.println(standardApplePredicate.test(new Apple("red", 150.0)));

    这将输出:

That’s it for Java Predicate functional interface.

Java谓词功能接口就是这样。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17072/java-predicate

java 8 谓词

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值