Home > Java > javaTutorial > Java Example - Array Union

Java Example - Array Union

黄舟
Release: 2017-02-21 09:43:52
Original
1393 people have browsed it

The following example demonstrates how to use the union () method to determine whether arrays are equal:

/*
 author by w3cschool.cc
 文件名:Main.java
 */
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 = { "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);
    }
}
Copy after login

The output result of the above code is:

并集的结果如下:
1
2
3
4
5
6
Copy after login

The above is the Java example - array union. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template