F. Böller
F. Böller

Reputation: 4294

Check order of two elements in Java-8-Stream

I want to check the order of two elements in a Java-8-Stream. I have this Iterator-Solution:

public static boolean isBefore (A a1,
                                A a2,
                                Stream<A> as) {
    Iterator<A> it = as.iterator ();
    while (it.hasNext ()) {
        A a = it.next ();
        if (a == a1) {
            return true;
        } else if (a == a2) {
            return false;
        }
    }
    throw new IllegalArgumentException (
        a1 + " and + " a2 + " arent elements of the stream!");
}

Is there a solution without iterators in a more functional/non imperative style?

Upvotes: 1

Views: 198

Answers (1)

Eran
Eran

Reputation: 393781

It could be something like this

as.filter (a -> (a==a1) || (a==a2)).findFirst ()

And then check if the result is a1 or a2 or empty. I'm sorry I don't give a full solution, it's hard to do if from my smart phone

Upvotes: 3

Related Questions