Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the right order of a list using Java 8 Lambda Expressions?

Tags:

lambda

java-8

I'm having the following method

private <T> void verify(String message, Supplier<T> targetSupplier,
        Predicate<T> predicate) {
    String verification = "verify that " + message;
    System.out.println(" -> " + verification);
    long start = System.currentTimeMillis();
    while ((System.currentTimeMillis() - start) < timeoutInMs) {
        try {
            T target = targetSupplier.get();
            if (predicate.test(target)) {
                return Verification.ok();
            }
            result = Verification.ko();
        } catch (NotFoundException e) {
            result = Verification.notFound();
        }
    }
}

and a

    List<String> ABC

How can I check if ABC is in ascending/descending order using Java 8 lambda expressions?

Many thank

like image 327
Nguyen Vu Hoang Avatar asked Jul 06 '14 16:07

Nguyen Vu Hoang


1 Answers

I'll answer the part about checking whether the list elements are in the right order. (I don't know what the verify method and arguments in the question are intended for.)

Stream operations work well for processing individual values in a collection (or other stream source), but they work less well for operating on adjacent elements. If you have a random-access collection, then it usually works to use the stream-of-indexes technique and pull out adjacent elements from the list by index and compare them using an ordering predicate.

Since you want to determine whether all the elements are ordered, use Stream.allMatch to combine the results of the ordering predicate applied to all adjacent pairs.

List<String> ABC = ... ;
boolean sortedAscending =
    IntStream.range(0, ABC.size()-1)
        .allMatch(i -> ABC.get(i).compareTo(ABC.get(i+1)) <= 0));

This verifies that the list is sorted in ascending order. To check for descending order, just use greater-than instead of less-than in the predicate.

There is probably a clever way to use collectors to do something similar, but it seems likely to me that it would be more complex.

like image 138
Stuart Marks Avatar answered Oct 31 '22 07:10

Stuart Marks