【问题标题】:INTERSECT result of 2 ArrayList containing Integer values包含整数值的 2 个 ArrayList 的 INTERSECT 结果
【发布时间】:2012-07-13 10:24:50
【问题描述】:

我有两个 ArrayList 都包含 Integer 值。我的目标是获得比较这两个列表的相同/常见/重复值。换句话说(用 SQL 说法),我需要两个列表的 INTERSECT 结果,即出现在两个列表中的值。

示例:

ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);

ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(300);
list2.add(600);

我可以想到的一种实现/解决方案是循环列表中的一个,例如:

ArrayList<Integer> intersectList = new ArrayList<Integer>();

for (Integer intValue : list1) 
{
    if(list2.contains(intValue))
        intersectList.add(intValue);
}

在这种情况下,intersectList 将只包含 1 个要添加的 Integer 项,即 300,它同时出现在两个列表中。

我的问题是,有没有更好/最快/有效的方法来实现这个逻辑? Apache Commons 库中有任何可用的选项吗?任何其他想法/建议/cmets 表示赞赏。

注意:为了便于说明,我在这里只展示了 5 个项目和 2 个被添加到列表中的项目。在我的实时实现中,每个列表中会有超过 1000 个元素。因此,性能也是一个需要考虑的关键因素

【问题讨论】:

标签: java performance arraylist intersection


【解决方案1】:

如果您可以覆盖 list1 的结果:

list1.retainAll(list2);

否则先克隆/复制 list1。

但不确定性能。

【讨论】:

    【解决方案2】:
    list1.retainAll(list2)//for intersection
    

    【讨论】:

      【解决方案3】:

      如果您不想修改现有列表,请使用 org.apache.commons.collections 中的 ListUtils。

      ListUtils.intersection(list1, list2)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-05
        • 1970-01-01
        • 1970-01-01
        • 2017-06-05
        • 2021-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多