gpt4 book ai didi

java - 在 Java 中对集合进行连接和分离的最佳方法

转载 作者:行者123 更新时间:2023-11-29 08:46:35 25 4
gpt4 key购买 nike

在两个 ArrayList 上创建 andor 方法的最有效方法是什么?

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

我需要实现这两种方法(非常简单),但我需要高效地完成,因为我将andor 用于包含数百个字符串的集合。任何提示?

最佳答案

为了避免混淆,我将调用方法intersectionunion 作为ANDOR 的含义有点模棱两可。

有一个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。这有两个目的:

  1. SetO(1) containsO(n)列表。这有助于交叉情况。
  2. Set 保证唯一性。这有助于解决工会案件。

另请注意,我在执行操作之前复制了集合 - 因为 Java 按值传递引用而不是复制会导致原始集合被更改。

如果您需要保留顺序,则需要使用 LinkedHashSet,因为 HashSet 没有顺序。

关于java - 在 Java 中对集合进行连接和分离的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com