Close

Java 8 Streams - Stream.allMatch Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

boolean allMatch(Predicate<? super T> predicate)

This terminal-short-circuiting operation returns whether all elements match the provided predicate criteria. It returns 'false' on finding the first mismatch hence short-circuiting (just like boolean && operator).

If the stream is empty then this method returns true and the predicate is not evaluated.


Examples


package com.logicbig.example.stream;

import java.util.Arrays;
import java.util.List;

public class AllMatchExample {

public static void main(String... args) {
List<Integer> list = Arrays.asList(2, 4, 6, 8);
boolean b = list.stream().allMatch(i -> i % 2 == 0);
System.out.println(b);
}
}

Output

true




package com.logicbig.example;

import java.util.stream.Stream;

public class AllMatchExample {
public static void main (String[] args) {
Stream<String> stream = Stream.of("one", "two", "Three", "four");
boolean match = stream.allMatch(s -> s.length() > 0 &&
Character.isLowerCase(s.charAt(0)));
System.out.println(match);
}
}

Output

false
Original Post




An empty stream will return true

package com.logicbig.example.stream;

import java.util.ArrayList;

public class AllMatchExample2 {

public static void main(String... args) {
boolean b = new ArrayList<>().stream()
.allMatch(e -> false);
System.out.println(b);
}
}

Output

true




See Also