数组并集
求兩個數組的并集。
使用union()方法來計算兩個數組的并集。
完整代碼
import java.util.Arrays; import java.util.HashSet; import java.util.Set;public class Main {public static void main(String[] args) throws Exception {String[] arr1 = { "1", "2", "3" };String[] arr2 = { "7", "8", "9" };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);} }結果輸出
并集的結果如下: 3 2 1 9 8 7總結
- 上一篇: Java字符流的使用
- 下一篇: C++ 函数对象