0

I have given the two arrays

array 1 :  a, b, c, d
array 2 :  a, b, c 

I have used the

ArrayList<String> combine =  new ArrayList<String> ()

and all the elements in array 1 and array 2

By sorting, I have found

a , a , b , b , c , c , d 

Would you please tell me how to compare the elements in these two arrays and return the distinct items (d for example)?

3 Answers 3

1

Something like

ArrayList<String> charsA = new ArrayList<>();
charsA.addAll(Arrays.asList("a", "a", "b", "c", "d"));
ArrayList<String> charsB = new ArrayList<>();
charsB.addAll(Arrays.asList("a", "b", "c"));

charsA.removeAll(charsB);
System.out.println(charsA);

prints

[d]

Obviously use a different list if you don't want any of the two original to be affected.

The removeAll(Collection) method

Removes from this list all of its elements that are contained in the specified collection.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to do it with Arrays then you have to loop over both the arrays and compare values one by one. If you want to do it with ArraysLists then you can build your logic around contains() and remove() methods.

Comments

0
    List<String> list1 = new ArrayList<String>();
    list1.add("a");
    list1.add("b");
    list1.add("c");
    list1.add("d");

    List<String> list2 = new ArrayList<String>();
    list2.add("a");
    list2.add("b");
    list2.add("c");

    List<String> distinctList = new ArrayList<String>();

    for (String string : list1) {
        if (!list2.contains(string)) {
            distinctList.add(string);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.