在Java中查找N个列表之间的公共元素 [英] Finding the common elements between N lists in Java

查看:329
本文介绍了在Java中查找N个列表之间的公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个Java程序来查找任意数量的整数(任意长度)的列表或数组的交集(公共元素).我想Java列表可能有一个有用的方法可以实现此目的,但是我正在看一下API却找不到它.

I need to write a Java program that finds the intersection (common elements) of an arbitrary number of lists or arrays of integers (of arbitrary length). I guess that Java Lists may have a useful method in order to achieve this, but I am taking a look at the API and can´t find it.

有任何提示吗?

推荐答案

通过将一个列表的元素复制到新列表中并使用retainAll,可以找到两个列表之间的公共元素:

You can find the common elements between two lists by copying the elements of one list into a new list, and using retainAll:

List<T> commonElements = new ArrayList<>(list1);
commonElements.retainAll(list2);

这可以扩展到n列表,因为n列表中的公共元素是[第一个n-1列表中的公共元素]和第[c1>个元素]的公共元素列表]:

This can be extended to n lists, since the common elements in n lists are the common elements of [the common elements of the first n-1 lists] and the [elements of the n-th list]:

commonElements.retainAll(list3);
commonElements.retainAll(list4);
...

例如

<T> List<T> commonElements(Iterable<? extends List<? extends T>> lists) {
  Iterator<? extends List<? extends T>> it = lists.iterator();
  List<T> commonElements = new ArrayList<T>(it.next());
  while (it.hasNext()) {
    commonElements.retainAll(it.next());
  }
  return commonElements;
}

请注意,如果列表为空,这将失败并显示NoSuchElementException.通过在第一个it.next()之前添加对it.hasNext()的检查,可以轻松处理这种情况.

Note that this will fail with a NoSuchElementException if lists is empty. It is straightforward to handle for this case, by adding a check for it.hasNext() before the first it.next().

这篇关于在Java中查找N个列表之间的公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆