如何比较2个java字符串数组并删除如果具有相同的值

时间:2010-11-28 07:03:56

标签: arrays string compare duplicates

我有2个字符串数组,

  str1[] = {"a","b","aa","c"} 

  str2[] = {"aa","a","b","c","d"}

如果在string [],预期结果,str3 [] = {“d”}

中存在,我如何比较和删除值?

提前致谢

2 个答案:

答案 0 :(得分:2)

在这些操作之后,

ts1将在其中包含“d”。

String str1[] = {"a","b","aa","c"};
String str2[] = {"aa","a","b","c","d"};
TreeSet ts1 = new TreeSet(Arrays.asList(str2));
ts1.removeAll(Arrays.asList(str1));

答案 1 :(得分:0)

将数组转换为列表并将它们添加到一个将自动删除重复项的集合中。使用Set接口的toArray()方法将元素作为数组获取。

    String[] str1 = {"a","b","aa","c"};
    String[] str2 = {"aa","a","b","c","d"};

    Set set = new HashSet();
    set.addAll(Arrays.asList(str1));//add first array to set, removes duplicates
    set.addAll(Arrays.asList(str2));//add second array to set, removes duplicates
    String[] str3 = (String[])set.toArray(new String[set.size()]);//convert back to array