3

I would like to get unique values from two Collection objects. How would I do that? Example: Let us take two ArrayLists:

List bag1 = new ArrayList(); 
List bag2 = new ArrayList();

bag1.add("1");
bag1.add("2");
bag1.add("3");
bag1.add("7");
bag1.add("8");
bag1.add("9");

bag2.add("4");
bag2.add("5");
bag2.add("6");
bag2.add("7");
bag2.add("8");
bag2.add("9");

I need to get a result like --> 1,2,3 from bag1 and 4,5,6 from bag2

Could you please help me out?

5 Answers 5

1

Two things:

  1. Use org.apache.commons.collections.CollectionUtils.disjunction(Collection a, Collection b);
  2. Bag isn't the best variable name for a list. :)
Sign up to request clarification or add additional context in comments.

Comments

0

You should take a look at Sets instead. The Java Collection has a few classes which deal with this. The idea is you could just the the set difference between the two collections, and you'll get your answer.

2 Comments

Thank you for the Answer. However one interviewer asked me how to get it done if you use ArrayList Object. Appreciate your time to look into this question.
If its an interviewer, shouldn't you do your due diligence instead of asking for the answer outright?
0

Use a 'set' to store your data. That way your collection will have unique elements as and when you add elements to the set.

See the javadoc over here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Set.html

Comments

0

have you tried...

bag1.removeAll(bag2);

If you want to keep bag1 and bag2 intact you can use a Set variable and pass all values of bag1 into the Set and then check for contains() like

    Set set = new HashSet();
    set.addAll(bag2);
    for(Object o: bag1){
        if(!set.contains(o)){
            // Do whatever you want with bag1 elements
        }
    }
    set.clear();

    set.addAll(bag1);
    for(Object o: bag2){
        if(!set.contains(o)){
            // Do whatever you want with bag2 elements
        }
    }

Comments

0

Use the removeAll method define in the Set interface.

Set intersect = new TreeSet(bag1);  
intersect.removeAll(bag2);  
List unique1 = Arrays.asList(intersect);  

intersect = new TreeSet(bag2);  
intersect.removeAll(bag1);  
List unique2 = Arrays.asList(intersect);  

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.