Merge arrays using collections

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;

public class array_union {
    public static void main(String[] args) {
        String[] arr1={"1","2","3"};
        String[] arr2={"3","4","5","6"};
        String[] result=union(arr1,arr2);
        System.out.println("数组合并后结果如下:");
        for (String str:result){
            System.out.print(str+" ");
        }
    }
    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);
    }
}

The output result is:

The results of array merging are as follows: 1 2 3 4 5 6

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>