Java 中的谓词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2955043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:54:31  来源:igfitidea点击:

Predicate in Java

javaguavapredicate

提问by srikanth

I am going through the code which uses Predicatein Java. I have never used Predicate. Can someone guide me to any tutorial or conceptual explanation of Predicateand its implementation in Java?

我正在浏览Predicate在 Java中使用的代码。我从来没有用过Predicate。有人可以指导我了解有关PredicateJava 及其实现的任何教程或概念说明吗?

采纳答案by polygenelubricants

I'm assuming you're talking about com.google.common.base.Predicate<T>from Guava.

我假设你说的是com.google.common.base.Predicate<T>番石榴。

From the API:

从API:

Determines a trueor falsevalue for a given input. For example, a RegexPredicatemight implement Predicate<String>, and return true for any string that matches its given regular expression.

确定给定输入的atruefalse值。例如, aRegexPredicate可能实现Predicate<String>,并为匹配其给定正则表达式的任何字符串返回true。

This is essentially an OOP abstraction for a booleantest.

这本质上是boolean测试的 OOP 抽象。

For example, you may have a helper method like this:

例如,您可能有这样的辅助方法:

static boolean isEven(int num) {
   return (num % 2) == 0; // simple
}

Now, given a List<Integer>, you can process only the even numbers like this:

现在,给定 a List<Integer>,您只能像这样处理偶数:

    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    for (int number : numbers) {
        if (isEven(number)) {
            process(number);
        }
    }

With Predicate, the iftest is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables, which have many utility methods that takes Predicate.

使用Predicateif测试被抽象为一个类型。这允许它与 API 的其余部分进行互操作,例如Iterables,它们具有许多使用Predicate.

Thus, you can now write something like this:

因此,您现在可以编写如下内容:

    Predicate<Integer> isEven = new Predicate<Integer>() {
        @Override public boolean apply(Integer number) {
            return (number % 2) == 0;
        }               
    };
    Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);

    for (int number : evenNumbers) {
        process(number);
    }

Note that now the for-each loop is much simpler without the iftest. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers, by filter-ing using a Predicate.

请注意,现在没有if测试的 for-each 循环要简单得多。我们通过定义Iterable<Integer> evenNumbers,通过filter-ing 使用 a达到了更高的抽象级别Predicate

API links

接口链接



On higher-order function

关于高阶函数

Predicateallows Iterables.filterto serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbersexample above. Suppose we want to test if all numbers are positive. We can write something like this:

Predicate允许Iterables.filter充当所谓的高阶函数。就其本身而言,这提供了许多优点。以List<Integer> numbers上面的例子为例。假设我们要测试是否所有数字都是正数。我们可以这样写:

static boolean isAllPositive(Iterable<Integer> numbers) {
    for (Integer number : numbers) {
        if (number < 0) {
            return false;
        }
    }
    return true;
}

//...
if (isAllPositive(numbers)) {
    System.out.println("Yep!");
}

With a Predicate, and interoperating with the rest of the libraries, we can instead write this:

使用Predicate, 并与其他库互操作,我们可以这样写:

Predicate<Integer> isPositive = new Predicate<Integer>() {
    @Override public boolean apply(Integer number) {
        return number > 0;
    }       
};

//...
if (Iterables.all(numbers, isPositive)) {
    System.out.println("Yep!");
}

Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.

希望您现在可以看到例程的更高抽象中的值,例如“按给定谓词过滤所有元素”、“检查所有元素是否满足给定谓词”等,从而使代码更好。

Unfortunately Java doesn't have first-class methods: you can't pass methodsaround to Iterables.filterand Iterables.all. You can, of course, pass around objectsin Java. Thus, the Predicatetype is defined, and you pass objectsimplementing this interface instead.

不幸的是,Java 没有一流的方法:您不能将方法传递给Iterables.filterIterables.all。当然,您可以在 Java 中传递对象。因此,Predicate类型已定义,您可以传递实现此接口的对象

See also

也可以看看

回答by techzen

You can view the java docexamples or the example of usage of Predicate here

您可以在此处查看java doc示例或 Predicate 的使用示例

Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:

基本上,它用于根据您可能拥有的任何特定条件过滤结果集中的行,并为满足您的条件的行返回 true:

 // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    resultset.beforeFirst();
    resultset.setFilter(filter);

回答by Michael Aaron Safyan

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

谓词是返回真/假(即布尔值)值的函数,而不是真/假(即布尔值)值的命题。在 Java 中,不能拥有独立的函数,因此可以通过为表示谓词的对象创建接口来创建谓词,然后提供实现该接口的类。谓词接口的示例可能是:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

然后你可能有一个实现,例如:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

为了更好地理解概念,您可能需要阅读一阶逻辑。

Edit
There is a standard Predicateinterface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicateinterface from Guava.

编辑Java 8 中的 Java API定义了
一个标准的Predicate接口(java.util.function.Predicate)。在 Java 8 之前,您可能会发现重用com.google.common.base.Predicate接口很方便番石榴

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> trueto a function instead of defining a named Tautology subclass like the above.

另请注意,从 Java 8 开始,使用 lambda 编写谓词要简单得多。例如,在 Java 8 及更高版本中,可以传递p -> true给函数,而不是像上面那样定义命名的 Tautology 子类。

回答by jai

Adding up to what Michealhas said:

加上迈克尔所说的:

You can use Predicate as follows in filtering collections in java:

您可以在 Java 中过滤集合中使用 Predicate 如下:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

一种可能的谓词可以是:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

用法:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);