简体   繁体   English

使用 java 合并两个字符串数组 object

[英]Merge Two String array object using java

public class MergeNames {
    public static void main(String[] args) {
        String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
        String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
        int na1 = names1.length;
        int na2 = names2.length;
        String [] result = new String[na1 + na2];
        System.arraycopy(names1, 0, result, 0, na1);
        System.arraycopy(names2, 0, result, na1, na2);
        System.out.println(Arrays.toString(result));
    }
}

I created Two Array Object String and Assign Same String values.我创建了两个数组 Object 字符串并分配相同的字符串值。 After need to merge the two String array object into another String array Object.之后需要将两个String数组object合并成另一个String数组Object。

Note: Without no duplication注:无重复

I want output like ["Ava", "Emma", "Olivia", "Sophia", "Emma"]我想要 output 像 [“Ava”、“Emma”、“Olivia”、“Sophia”、“Emma”]

You can use Java Stream API the Stream.of() .你可以使用Java Stream API Stream.of() See the example for better understanding.请参阅示例以获得更好的理解。

Reference Code参考代码

public class Main {
    public static <T> Object[] mergeArray(T[] arr1, T[] arr2)   
    {   
        return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();   
    }   
    public static void main(String[] args) {
        String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
        String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
        
        Object [] result = mergeArray(names1, names2);
        
        System.out.println(Arrays.toString(result));
    }
}

Output Output

[Ava, Emma, Olivia, Sophia]

You have small mistake你有小错误

String [] result = new String[na1 + na2];

not int不是整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM