program story

자바의 술어

inputbox 2020. 8. 23. 09:07
반응형

자바의 술어


PredicateJava에서 사용하는 코드를 살펴 보겠습니다 . 나는 한 번도 사용하지 않았습니다 Predicate. 누군가 Predicate가 Java에 대한 자습서 또는 개념 설명 및 구현을 안내해 줄 수 있습니까 ?


나는 당신이 com.google.common.base.Predicate<T>구아바에서 이야기하고 있다고 가정하고 있습니다 .

API에서 :

주어진 입력에 대한 true또는 false값을 결정합니다 . 예를 들어 a RegexPredicate는를 구현 Predicate<String>하고 주어진 정규식과 일치하는 모든 문자열에 대해 true를 반환 할 수 있습니다 .

이것은 본질적으로 boolean테스트를 위한 OOP 추상화입니다 .

예를 들어 다음과 같은 도우미 메서드가있을 수 있습니다.

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

이제가 주어지면 다음 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);
        }
    }

를 사용 Predicate하면 if테스트가 유형으로 추상화됩니다. 이를 통해를 사용하는 Iterables많은 유틸리티 메서드가있는 과 같은 나머지 API와 상호 운용 할 수 있습니다 Predicate.

따라서 이제 다음과 같이 작성할 수 있습니다.

    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);
    }

이제 for-each 루프는 if테스트 없이 훨씬 더 간단합니다 . 우리는 정의하여 abtraction의 높은 수준에 도달했습니다 Iterable<Integer> evenNumbers에 의해, filter사용 a -ing Predicate.

API 링크


고차 함수

PredicateIterables.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<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 methods around to Iterables.filter and Iterables.all. You can, of course, pass around objects in Java. Thus, the Predicate type is defined, and you pass objects implementing this interface instead.

See also


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:

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 Predicate interface (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.Predicate interface from Guava.

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 -> true to a function instead of defining a named Tautology subclass like the above.


You can view the java doc examples or the example of usage of Predicate here

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:

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

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

Adding up to what Micheal has said:

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

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);

참고URL : https://stackoverflow.com/questions/2955043/predicate-in-java

반응형