I want to get a false value using a single stream chain which ends with allMatch terminal operation.
However, I found out that due to the design of the allMatch operation, it will return true when it processes an empty stream.
For example, the following codes return true because the filtered stream is empty down the pipeline.
List<String> list = Arrays.asList("abc", "efg", "hij");
boolean isAllStartsWith1 = list.stream().filter(s-> s.endsWith("x")).allMatch(s->s.startsWith("1"));
System.out.println(isAllStartsWith1);
In order to get my expected result (false), I would need to collect the stream into a temporary list and add additional checking to confirm that if it is empty before passing to allMatch operation for the final processing. This makes the whole processes look very clunky, is there any more elegant solution to this problem?
List<String> list = Arrays.asList("abc", "efg", "hij");
List<String> filteredList = list.stream().filter(s-> s.endsWith("x")).collect(Collectors.toList());
boolean isAllStartsWith1 = !filteredList.isEmpty() && filteredList.stream().allMatch(s->s.startsWith("1"));
System.out.println(isAllStartsWith1);