I already added two answers I now removed but the problem kept nagging on me so I gave it a third try and this time it works including keeping allMatch
. Here is the code for method validate
.
public static boolean validate(Stream<Whatever> stream) {
final boolean[] streamNotEmpty = new boolean[1];
return stream.filter(elem -> {
streamNotEmpty[0] = true;
return true;
}).allMatch(Whatever::someCheck) && streamNotEmpty[0];
}
A shorter version would be
public static boolean validate(Stream<Whatever> stream) {
final boolean[] streamNotEmpty = new boolean[1];
return stream.allMatch(elem -> {
streamNotEmpty[0] = true;
return elem.someCheck();
}) && streamNotEmpty[0];
}
The idea behind this is that we want to know if there was at least one element in the stream, so I created a final boolean[]
where the value is changed within the filter-call. So at the end of the stream's processing we can check the stream for being empty or not and act accordingly when we return the result.
Here is a complete class including testcases to prove that - this time finally - I provided a valid solution.
import java.util.ArrayList;
import java.util.stream.Stream;
public class StreamTest {
public static boolean validate(Stream<Whatever> stream) {
final boolean[] streamNotEmpty = new boolean[1];
return stream.allMatch(elem -> {
streamNotEmpty[0] = true;
return elem.someCheck();
}) && streamNotEmpty[0];
}
static class Whatever {
private boolean checkResult;
public Whatever() {
this(false);
}
public Whatever(boolean b) {
this.checkResult = b;
}
public boolean someCheck() {
return checkResult;
}
}
public final static void main(String[] args) {
ArrayList<Whatever> list = new ArrayList<>();
System.out.println("empty list: " + validate(list.stream()));
System.out.println("empty list parallel: " + validate(list.parallelStream()));
for (int i = 0; i < 10000; i++) {
list.add(new Whatever(true));
}
System.out.println("non empty true list: " + validate(list.stream()));
System.out.println("non empty true list parallel: " + validate(list.parallelStream()));
for (int i = 0; i < 10000; i += 1000) {
list.add(new Whatever(false));
}
System.out.println("non empty false list: " + validate(list.stream()));
System.out.println("non empty false list parallel: " + validate(list.parallelStream()));
}
}
The output when executing it is:
empty list: false
empty list parallel: false
non empty true list: true
non empty true list parallel: true
non empty false list: false
non empty false list parallel: false