简体   繁体   English

检查Java-8-Stream中两个元素的顺序

[英]Check order of two elements in Java-8-Stream

I want to check the order of two elements in a Java-8-Stream. 我想检查Java-8-Stream中两个元素的顺序。 I have this Iterator-Solution: 我有这个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? 是否有一个没有迭代器的解决方案,功能更强大/非命令式?

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. 然后检查结果是a1还是a2还是空的。 I'm sorry I don't give a full solution, it's hard to do if from my smart phone 对不起,我没有给出完整的解决方案,如果从我的智能手机上做起来很难

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM