0

I have 2 array list that contain strings:

List1 = [no, yes, ok, not]
List2 = [no, but, vote, check]

Now, how do I compare List1 with List2 and remove the words in List1 if the same word are found in List2. The sorted word(without the same word) are stored in another arraylist.

Outcome should be like this:

List3 = [yes, ok, not]

4 Answers 4

4

If you want to store the result in a new list, you need to clone List1 first:

ArrayList list3 = (ArrayList) list1.clone();

or

ArrayList list3 = new ArrayList(list1);

Then use removeAll:

list3.removeAll(list2);
Sign up to request clarification or add additional context in comments.

Comments

1

ArrayList provides method to remove all object present in another list.

Refer Removing elements present in collection

In your case list1.removeAll(list2) should solve your problem

Comments

0

You can create third list , add to it your two lists and find in it third list same words. When you find them , delete one.So you'll check your third list with equals().

Comments

0

I suppose you didn't know about the removeAll(Collection c) method present for ArrayLists or just want another way of doing it.

Since you mention that you need to remove the duplicated words from list1, initialize a HashSet and add all the values in list2 to the Set, like so,

Set<String> set = new HashSet<String>();
for(String s: list2)
    set.add(s);

Now, do the same with a clone of list1, taking care to remove the strings from list1.

String[] list3 = new String[list1.size()];
list1.toArray(list3);
for(String s: list3)
    if(!set.add(s))
        list1.remove(s);

This is done in O(n) time, but takes some auxiliary storage. Please let me know if this solved your problem.

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.