-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeHashSet.java
More file actions
36 lines (28 loc) · 954 Bytes
/
MergeHashSet.java
File metadata and controls
36 lines (28 loc) · 954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**以下实例演示了如何使用 union ()方法来计算两个数组的并集
*/
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MergeHashSet {
public static void main(String[] args) throws Exception {
String[] arr1 = { "1", "2", "3" };
String[] arr2 = { "4", "5", "6" };
String[] result_union = union(arr1, arr2);
System.out.println("并集的结果如下:");
for (String str : result_union) {
System.out.println(str);
}
}
// 求两个字符串数组的并集,利用set的元素唯一性
public static String[] union(String[] arr1, String[] arr2) {
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str);
}
for (String str : arr2) {
set.add(str);
}
String[] result = { };
return set.toArray(result);
}
}