3

I have two lists. For example:

A = {21, 41, 96, 02}
B = {21, 96, 32, 952, 1835}

What I want is this as a result: R = {32, 952, 1835}

Like this: Example Picture

After this I want to add the result R to A:

A = {21, 41, 96, 02, 32, 952, 1835}
9
  • 3
    How is that going for you? Commented Oct 28, 2014 at 9:18
  • 2
    Did you wrote any code ? Please, post it. Commented Oct 28, 2014 at 9:18
  • 1
    And what is your question? Commented Oct 28, 2014 at 9:18
  • @JamesFox No. Please look at the image. I only want the red part Commented Oct 28, 2014 at 9:22
  • are you want to compare these two values ?? Commented Oct 28, 2014 at 9:22

4 Answers 4

3

It's simple :)

List<Integer> a = new ArrayList<>(Arrays.asList(21, 41, 96, 02));
List<Integer> b = new ArrayList<>(Arrays.asList(21, 96, 32, 952, 1835));

b.removeAll(a)

// now list b contains (32, 952, 1835)

a.addAll(b);

// now list a contains (21, 41, 96, 02, 32, 952, 1835)
Sign up to request clarification or add additional context in comments.

2 Comments

This answers part of the question, finding out R.
@vegemite4me right - I've missed second part - thanks!
1

So, you want the set reunion of those two collections. That's what sets are for.

HashSet<Integer> set = new HashSet<Integer>();
set.addAll(a);
set.addAll(b);

Comments

0

So you want to make A = A U B. To do this, you can search for each element of B in A and add the element to A if the search fails. However, making too much search on a list is not recommended.

I would recommend using a HashMap. Create a HashMap and loop through A and B putting anything you see into the map. After that, you can convert map back to a list.

[If you want the order to be the same as in the example, you should convert A to a map. Then you should go through B and for each failed map.get(element) you should be adding that element of B to A.]

Comments

0

Try this :

import org.apache.commons.collections.CollectionUtils;

[...]
    //  Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Collections.
    Collection disJointList = CollectionUtils.disjunction(a, b);  
    //To check
    for (Object object : disJointList) {  
            System.out.println(disJointList);  
            //output is {32, 952, 1835} 
    }   

    a.addAll( disJointList );

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.