【问题标题】:Fast way to get common items of two ordered iterables?获取两个有序迭代的常见项目的快速方法?
【发布时间】:2014-08-01 03:27:29
【问题描述】:

如何获得两个 ordered 可迭代对象的共同项目?是否有任何来自 apache commons 或 Guava 的库方法或任何使用快速算法的此类库?

【问题讨论】:

  • 你见过在 Java 8 中使用 lambda 表达式的新 for 循环吗?
  • 对此一无所知..顺便说一句我还没有使用Java 8..我在java 7上
  • 看看吧,你会觉得有趣的

标签: java guava apache-commons iterable


【解决方案1】:

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

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);
}

【讨论】:

  • 我不同意:List(4)List(1,2,4) 甚至没有进入循环。 List(1,4)List(1,2,4) 可以,但您需要将 4 添加到结果中。
  • 错字:E e1 = it1.hasNext(); -> E e1 = it1.next();E e2 ... 相同)
猜你喜欢
  • 2020-06-12
  • 2021-10-20
  • 2019-12-03
  • 2023-03-19
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多