Java中ArrayLists的交集和联合
有什么方法可以这样做吗? 我在找,但找不到任何。
另一个问题:我需要这些方法,所以我可以过滤文件。 有些是AND
过滤器,有些是OR
过滤器(就像在集合论中),所以我需要根据所有文件和包含这些文件的联合/相交ArrayLists进行过滤。
我应该使用不同的数据结构来保存文件吗? 还有什么可以提供更好的运行时间吗?
这是一个简单的实现,不使用任何第三方库。 优于retainAll
, removeAll
和addAll
主要优点是这些方法不会修改输入到方法的原始列表。
public class Test {
public static void main(String... args) throws Exception {
List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
System.out.println(new Test().intersection(list1, list2));
System.out.println(new Test().union(list1, list2));
}
public <T> List<T> union(List<T> list1, List<T> list2) {
Set<T> set = new HashSet<T>();
set.addAll(list1);
set.addAll(list2);
return new ArrayList<T>(set);
}
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
}
Collection(所以ArrayList也有):
col.retainAll(otherCol) // for intersection
col.addAll(otherCol) // for union
如果您接受重复,请使用List实现;如果您不接受,则使用Set实现:
Collection<String> col1 = new ArrayList<String>(); // {a, b, c}
// Collection<String> col1 = new TreeSet<String>();
col1.add("a");
col1.add("b");
col1.add("c");
Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}
// Collection<String> col2 = new TreeSet<String>();
col2.add("b");
col2.add("c");
col2.add("d");
col2.add("e");
col1.addAll(col2);
System.out.println(col1);
//output for ArrayList: [a, b, c, b, c, d, e]
//output for TreeSet: [a, b, c, d, e]
这篇文章相当老,但它是在寻找该主题时在谷歌上弹出的第一个。
我想给出一个使用Java 8流更新(基本上)在同一行中进行更新的更新:
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
List<T> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
如果任何人有一个更好/更快的解决方案让我知道,但这个解决方案是一个很好的单线程,可以方便地包含在方法中,而无需添加不必要的辅助类/方法,仍然保持可读性。
链接地址: http://www.djcxy.com/p/76089.html