CKTIS / Java
Predicate.or(): OR logico tra predicati
Combina due predicati in una condizione riutilizzabile. Il secondo predicato viene valutato solo se il primo restituisce `false`.
Versione: Java SE 21
Sintassi
default Predicate<T> or(Predicate<? super T> other)
Predicate<T> combined = first.or(other);
boolean matches = combined.test(value);Predicate.or() è un metodo di default di java.util.function.Predicate<T>. La chiamata first.or(other) richiede un argomento e restituisce un Predicate<T> senza verificare alcun valore. Il parametro Predicate<? super T> accetta un predicato per T o per un suo supertipo, per esempio un Predicate<Object> se first è un Predicate<String>.
Con combined.test(value) viene valutato prima first. Se restituisce true, il risultato è true e other non viene valutato. Se restituisce false, other verifica lo stesso valore e fornisce il risultato. Il risultato è false solo se entrambi i predicati restituiscono false. L’espressione first.test(value) || other.test(value) segue la stessa regola di valutazione a cortocircuito, ma produce un valore booleano anziché un predicato riutilizzabile.
La chiamata first.or(null) lancia subito una NullPointerException, anche se first restituisce sempre true. Non è lo stesso che passare null a test: in quel caso, il comportamento dipende dai predicati effettivamente valutati. Le eccezioni lanciate da uno di questi predicati si propagano al chiamante; se first lancia un’eccezione, other non viene valutato.
Esempi
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> startsWithA = name -> name.startsWith("A");
Predicate<String> atLeastFive = name -> {
System.out.println("length check: " + name);
return name.length() >= 5;
};
Predicate<String> matches = startsWithA.or(atLeastFive);
for (String name : new String[] {"Amy", "Bruno", "Bo"}) {
System.out.println(name + ": " + matches.test(name));
}
}
}Risultato
Amy: true length check: Bruno Bruno: true length check: Bo Bo: false
`Amy` soddisfa la prima condizione, quindi `length check: Amy` non viene stampato. La lunghezza viene verificata per `Bruno` e `Bo`: `Bruno` soddisfa la condizione perché ha almeno cinque caratteri, mentre `Bo` non la soddisfa.
Lezioni correlate
- Java · Lezione 62 · Base · Versione: 2