如何从java中的两个数组列表中获取公共项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23356968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:10:27  来源:igfitidea点击:

How to get the common items from two arraylists in java?

javaarraylist

提问by user3152686

I have two lists of Strings which contains around 100 string items in each list in which some are common.

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

I want to obtain the items which are common to both the lists and store it another list.

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

How can this be done. Please help.

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

采纳答案by niiraj874u

You can use retainAll method of List

您可以使用 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);
  }
}

This will print [b, b]

这将打印 [b, b]

回答by Sajad Karuthedath

try Collection#retainAll()

尝试集合#retainAll()

listA.retainAll(listB);

回答by George Sovetov

What you want is called set intersection. (Or multiset, if you want see several duplicates.)

你想要的叫做集合交集。(或者多集,如果你想看到几个重复。)

Simple but efficient solution is to sort both arrays and iterate over them.

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

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

If your string is long enough, you should add to HashSetstrings from first list and iterate over second array checking if element is in set.

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