【问题标题】:How to get the common items from two arraylists in java? [duplicate]如何从java中的两个arraylists中获取公共项目? [复制]
【发布时间】:2014-06-14 22:29:05
【问题描述】:

我有两个字符串列表,每个列表中包含大约 100 个字符串项,其中一些是常见的。

我想获取两个列表共有的项目并将其存储在另一个列表中。

如何做到这一点。请帮忙。

【问题讨论】:

  • 可以有重复吗?即,可以有a, b, b, cx, b, b, a 而你想要bs 吗?
  • 为在本网站上重复的问题写答案并且不付出努力只会促使人们继续不付出努力但仍然得到答案。

标签: java arraylist


【解决方案1】:

可以使用List的retainAll方法

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainClass {
  public static void main(String args[]) {
    String orig[] = { "a", "b", "b", "c" };
    String act[] = { "x", "b", "b", "y" };
    List origList = new ArrayList(Arrays.asList(orig));
    List actList = Arrays.asList(act);
    origList.retainAll(actList);
    System.out.println(origList);
  }
}

这将打印 [b, b]

【讨论】:

    【解决方案2】:

    试试Collection#retainAll()

    listA.retainAll(listB);
    

    【讨论】:

      【解决方案3】:

      你想要的叫做集合交集。 (或多集,如果您想查看多个重复项。)

      简单但有效的解决方案是对两个数组进行排序并对其进行迭代。

      for(int i = 0; i < a.length(); )
      {
          for(int j = 0; j < b.length(); )
          {
              int comparison = a[i].compareTo(b[j]);
              if(comparison == 0)
              {
                  // Add a[i] or b[j] to result here.
                  // If you don't want duplicate items
                  // in result, compare a[i] to
                  // last item in result and add 
                  // only if a[i] is strictly greater.
      
                  ++i;
                  ++j;
              }
              else if(comparison < 0)
                  ++i;
              else
                  ++j
          }
      }
      

      如果你的字符串足够长,你应该从第一个列表中添加到HashSet 字符串并遍历第二个数组检查元素是否在集合中。

      【讨论】:

        猜你喜欢
        • 2021-07-21
        • 2022-01-02
        • 1970-01-01
        • 2019-12-22
        • 2019-08-14
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        相关资源
        最近更新 更多