快速获取两个有序迭代的常见项目?

时间:2014-06-11 07:09:10

标签: java guava apache-commons iterable

如何获得两个有序迭代的常见项?是否有来自apache commons或Guava的任何库方法或任何使用快速算法的库?

1 个答案:

答案 0 :(得分:2)

假设您的元素具有可比性:

List<E> res = new ArrayList<>();
Iterator<E> it1 = orderedIterables1.iterator();
Iterator<E> it2 = orderedIterables2.iterator();
if(!it1.hasNext() || !it2.hasNext()) { // is one of the iterables empty?
    return res;
}
E e1 = it1.next();
E e2 = it2.next();
while(it1.hasNext() && it2.hasNext()) {  // go through each iterable
    int c = e1.compareTo(e2);
    if(c == 0) {
        res.add(e1);
        e1 = it1.next();
        e2 = it2.next();
    } else if(c < 0) {   // e1 is lesser than e2, so take next e1
        e1 = it1.next();
    } else {             // e2 is lesser than e1, so take next e2
        e2 = it2.next();
    }
}
// one of the iterables has now been exhausted 
int c = e1.compareTo(e2);
if(c < 0) {
    while(c < 0 && it1.hasNext()) {  // while e1 < e2, let's take the next e1!
        e1 = it1.next();
        c = e1.compareTo(e2);
    }
} else if(c > 0) {
    while(c > 0 && it2.hasNext()) {  // while e2 < e1, let's take the next e2!
        e2 = it2.next();
        c = e1.compareTo(e2);
    }
}
if(c == 0) {
    res.add(e1);
}