在两个 ArrayList 上创建 and
和 or
方法的最有效方法是什么?
//not coded in java
HashSet<String> first = {"hello", "to", "you"}
HashSet<String> second = {"hello", "to", "me"}
HashSet<String> and = and(first, second) = {"hello", "to"}
HashSet<String> or = or(first, second) = {"hello", "to", "you", "me"}
我需要实现这两种方法(非常简单),但我需要高效地完成,因为我将and
和or
用于包含数百个字符串的集合。任何提示?
最佳答案
为了避免混淆,我将调用方法intersection
和union
作为AND
和OR
的含义有点模棱两可。
有一个retainAll
Set
上的方法,它将完成交集的工作。你需要注意我在 another answer (of mine) on SO 中的警告.
有一个addAll
Collection
上的方法将完成联合的工作。
这是一个例子:
public static void main(String[] args) throws Exception {
final Set<String> first = new HashSet<>(Arrays.asList("hello", "to", "you"));
final Set<String> second = new HashSet<>(Arrays.asList("hello", "to", "me"));
System.out.println(intersection(first, second));
System.out.println(union(first, second));
}
public static Set<String> intersection(final Set<String> first, final Set<String> second) {
final Set<String> copy = new HashSet<>(first);
copy.retainAll(second);
return copy;
}
public static Set<String> union(final Set<String> first, final Set<String> second) {
final Set<String> copy = new HashSet<>(first);
copy.addAll(second);
return copy;
}
注意使用 Set
而不是 List
。这有两个目的:
Set
有O(1)
contains
而O(n)
为列表
。这有助于交叉情况。Set
保证唯一性。这有助于解决工会案件。
另请注意,我在执行操作之前复制了集合 - 因为 Java 按值传递引用而不是复制会导致原始集合被更改。
如果您需要保留顺序,则需要使用 LinkedHashSet
,因为 HashSet
没有顺序。
关于java - 在 Java 中对集合进行连接和分离的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984787/