Using predicate in java

Uses of Interface
java.util.function.Predicate

Contains the collections framework, some internationalization support classes, a service loader, properties, random number generation, string parsing and scanning classes, base64 encoding and decoding, a bit array, and several miscellaneous utility classes.

Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections.

Uses of Predicate in java.io

Uses of Predicate in java.util

If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional .

Uses of Predicate in java.util.concurrent

ForkJoinPool (int parallelism, ForkJoinPool.ForkJoinWorkerThreadFactory factory, Thread.UncaughtExceptionHandler handler, boolean asyncMode, int corePoolSize, int maximumPoolSize, int minimumRunnable, Predicate saturate, long keepAliveTime, TimeUnit unit)

Uses of Predicate in java.util.function

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

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

Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.

Uses of Predicate in java.util.regex

Uses of Predicate in java.util.stream

Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate.

Adapts a Collector to one accepting elements of the same type T by applying the predicate to each input element and only accumulating if the predicate returns true .

Returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate.

Returns a Collector which partitions the input elements according to a Predicate , and organizes them into a Map> .

Returns a Collector which partitions the input elements according to a Predicate , reduces the values in each partition according to another Collector , and organizes them into a Map whose values are the result of the downstream reduction.

Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Interface Predicate

Type Parameters: T — the type of the input to the predicate Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

This is a functional interface whose functional method is test(Object) .

Method Summary

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

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

Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.

Method Details

test

and

Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. When evaluating the composed predicate, if this predicate is false , then the other predicate is not evaluated. Any exceptions thrown during evaluation of either predicate are relayed to the caller; if evaluation of this predicate throws an exception, the other predicate will not be evaluated.

negate

or

Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another. When evaluating the composed predicate, if this predicate is true , then the other predicate is not evaluated. Any exceptions thrown during evaluation of either predicate are relayed to the caller; if evaluation of this predicate throws an exception, the other predicate will not be evaluated.

isEqual

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

not

Returns a predicate that is the negation of the supplied predicate. This is accomplished by returning result of the calling target.negate() .

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java Predicate with Examples

In mathematics, a predicate is commonly understood as a boolean-valued functionP:X ? ‘ , called the predicate on X. Let’s learn how the Java Predicate interface helps write filter expressions easily.

1. When to use a Predicate

Introduced in Java 8, Predicate is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

So, where do you think, we can use these true/false returning functions in day-to-day programming? I will say we can use predicates anywhere we need to evaluate a condition on a collection of objects such that evaluation can result either in true or false.

For example, we can use predicates in these real-life usecases:

  • Find all children born after a particular date
  • Pizzas ordered within a specific time range
  • Employees older than a certain age
  • and so on…

As mentioned earlier, predicates evaluate an expression and return a boolean value. Now let us see a few examples of creating simple predicates with a simple example.

Predicate isAdult = e -> e.getAge() > 18; Predicate isMale = p -> p.getGender().equalsIgnoreCase("M");

We can create a complex Predicate by mixing two or more predicates.

Predicate isAdultMale= isAdult.and(isMale); Predicate isAdultOrMale = isAdult.or(isMale);

It is possible to create a reverse predicate of an existing Predicate using the negate() method.

Predicate isMinor = isAdult.negate();

3. Using Predicate with Streams

As we know, Predicate is a functional interface, meaning we can pass it in lambda expressions wherever a predicate is expected. For example, one such method is filter() method from Stream interface.

/** * Returns a stream consisting of the elements of this stream that match the given predicate. */ Stream filter(Predicate predicate);

So, essentially we can use stream and predicate to –

  • first filter certain elements from a group, and
  • then, perform some operations on filtered elements.

In the following example, we find all the male employees using the Predicate isMale and collect all male employees into a new List.

Predicate isMale = p -> p.getGender().equalsIgnoreCase("M"); List maleEmployeeList = employeeList.stream().filter(isMale).toList();

Note that if we want to use two arguments to test a condition, we can also use BiPredicate class.

BiPredicate isAdultMale = (p1, p2) -> p1 > 18 && p2.equalsIgnoreCase("M"); List adultMalesList = employeeList.stream() .filter(x -> isAdultMale.test(x.getAge(), x.getGender())) .toList();
  • Predicates move the conditions (sometimes business logic) to a central place. This helps in unit-testing them separately.
  • Any code change need not be duplicated into multiple places; thus, predicates improve code maintenance.
  • The names predicates such as “isAdultFemale()” are much more readable than writing a if-else block.

Источник

Читайте также:  Unit testing java intellij
Оцените статью