如何从java中的两个数组中删除重复的字符串?

时间:2014-05-08 06:06:37

标签: java arrays string duplicate-removal

这是我的jsp页面。

<body>
    <%

        String a[] = {"PAK", "ENG", "IND", "USA"};
        String b[] = {"ON", "UK","IND","ENG","SA"};
        String[] Filterjoined = ObjectArrays.concat(a, b, String.class);
        out.println(Arrays.toString(Filterjoined));
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Filterjoined.length; i++) {
            boolean found = false;
            for (int j = i + 1; j < Filterjoined.length; j++) {
                if (Filterjoined[j].equals(Filterjoined[i])) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (sb.length() > 0) {
                    sb.append(',');
                }
                sb.append(Filterjoined[i]);
            }
        }
        out.println("<br>");
        out.println(sb);
    %>
</body>

这里我的输出为PAK,USA,ON,UK,IND,ENG,SA,但如果字符串重复,我需要从两个数组中删除字符串。即,预期输出为:PAK,USA,ON,UK,ENG,SA因为IND在两个数组中都有重复,所以我需要删除它,剩下的元素必须显示。谢谢你的回复

2 个答案:

答案 0 :(得分:4)

这是如何使用该集。

Set<String> joined = new HashSet<String>(Arrays.asList(a));
joined.addAll(Arrays.asList(b));
String[] joinedArray = joined.toArray(new String[joined.size()]);

答案 1 :(得分:0)

Java已经拥有了在没有第三方库等的情况下完成任务所需的一切。使用以下解决方案:

String a[] = {"PAK", "ENG", "IND", "USA"};
String b[] = {"ON", "UK","IND","ENG","SA"};

/* Convert your arrays to lists */
final List<String> listA = Arrays.asList(a);
final List<String> listB = Arrays.asList(b);

/* Create another list holding 'duplicate' elements */
final List<String> duplicatesList = new ArrayList<String>(listA);
duplicatesList.retainAll(listB);

/* Finally create a resulting list as a + b - duplicates */
final List<String> result = new ArrayList<String>(listA);
result.addAll(listB);
result.removeAll(duplicatesList);

System.out.println(result);