如何返回包含两个数组中出现的值的数组?而且没有重复

时间:2019-04-18 15:35:13

标签: java arrays

我想传递两个名称数组,这样它将返回一个包含出现在两个或两个数组中的名称的数组。返回的数组应该没有重复。

例如,调用MergeNames.uniqueNames(new String[]{'Ava', 'Emma', 'Olivia'}, new String[]{'Olivia', 'Sophia', 'Emma'})应该以任意顺序返回包含Ava,Emma,Olivia和Sophia的数组。

需要基本实现uniqueNames方法。抱歉,我是Java编程的新手,并尝试通过编码挑战来成为一名开发人员。

public class MergeNames {

    public static String[] uniqueNames(String[] names1, String[] names2) {
        throw new UnsupportedOperationException("Waiting to be implemented.");      
    }

    public static void main(String[] args) {
        String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
        String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
        System.out.println(String.join(", ", MergeNames.uniqueNames(names1, names2))); // should print Ava, Emma, Olivia, Sophia
    }
}

******我的解决方案任何反馈欢迎******

import java.util.*;

public class MergeNames {

public static void main(String[] args) {

    String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
    String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};

    Set<String> mySet1 = new HashSet<String>(Arrays.asList(names1));
    Set<String> mySet2 = new HashSet<String>(Arrays.asList(names2));

    Set<String> union = new HashSet<String>(mySet1);
    union.addAll(mySet2);
    System.out.println("Union of the two Sets with no duplicate names : " + union);

}
}

我不确定为什么需要uniqueNames函数吗?

2 个答案:

答案 0 :(得分:1)

在注释中,您提到必须使用另一种方法来执行此操作,并将 joint数组作为参数返回给main() 。好的,我认为这意味着您必须将联合数组return回到main()“不作为参数”

您可以这样:

import java.util.*;

public class MergeNames 
{
    public static void main(String[] args) 
    {
        String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
        String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
        String[] Names = mergeNames(names1, names2);
        for(String n: Names)
            System.out.print(" "+ n);
    }

    public static String[] mergeNames(String[] n1, String[] n2)
    {
        Set<String> mySet1 = new HashSet<String>(Arrays.asList(n1));
        Set<String> mySet2 = new HashSet<String>(Arrays.asList(n2));
        Set<String> union = new HashSet<String>(mySet1);
        union.addAll(mySet2);
        return  union.toArray(new String[union.size()]);
    }
}

答案 1 :(得分:0)

如@junvar所建议,请看java.util.Set

  • 创建一个new java.util.TreeSet<String> myset
  • 遍历每个数组,并为每个名称值调用myset.add()。 Set将为您删除重复项
  • 要将集合转换回数组,请参见Converting Set<String> to String array

祝你好运!