Home > Mobile >  Looking for elegant way of solving Stream.allMatch equals to true when processing a potentially empt
Looking for elegant way of solving Stream.allMatch equals to true when processing a potentially empt

Time:04-19

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 = CollectionUtils.isEmpty(filteredList) ? false : filteredList.stream().allMatch(s->s.startsWith("1"));
                        
System.out.println(isAllStartsWith1);

CodePudding user response:

Change the original implementation :)

You want to know if there is any item in your list that does not start with 1, right?

(But I agree this double-negation is a bit hard to read)

atLeastOneThatDoesNotStartWithOne = list.stream()
            .filter(s -> s.endsWith("x"))
            .anyMatch(s -> !s.startsWith("1"));

allStartWith1 = ! list.stream()
            .filter(s -> s.endsWith("x"))
            .anyMatch(s -> !s.startsWith("1"));
    

This implementation might also be a faster (depending on the dataset), because it can stop after it encountered one failing case, instead of having to check all the items)

CodePudding user response:

You can count with .count() to return true if the result is greater than 0, false otherwise.

System.out.println(list.stream().filter(s -> s.endsWith("x")).count() > 0 ? true: false); 
  • Related