Question

This is my jsp page.

<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>

Here i'm getting output as PAK,USA,ON,UK,IND,ENG,SA but i need to delete string from both arrays if string has duplicated. i.e., expected output is:PAK,USA,ON,UK,ENG,SA because IND has duplicated in both arrays so i need to delete it,remaining elements has to display.Thanks for your reply

Was it helpful?

Solution 2

Java already has everything you need to do your task without third party libraries, etc. Use the following solution:

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);

OTHER TIPS

This is how to use the set.

Set<String> joined = new HashSet<String>(Arrays.asList(a));
joined.addAll(Arrays.asList(b));
String[] joinedArray = joined.toArray(new String[joined.size()]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top