[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 390
  • Last Modified:

ArrayList Comparistion

Hi

I have two arrayalist
 
ArrayList a = {2,3,4, 5,6}
ArrayList b = {1,2,3}

a-b = {4,5,6}
b-a = {1}

My question is there any built in fuction that will perform minus operation of two array list.
If there is no builtin how do we perform. I think there should be a built in not sure how we can perform
Can you help we a running example.

Thanks
0
basirana
Asked:
basirana
1 Solution
 
avsrivastavaCommented:
public boolean removeAll(Collection c)
http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractCollection.html#removeAll(java.util.Collection)

or iterator over one arraylist and keep using
public boolean remove(Object o)

http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html#remove(java.lang.Object)

Hope this helps.
0
 
basiranaAuthor Commented:
Thanks for Response Have great time
0
 
gambisticsCommented:
Here is an example of how to do that:

ArrayList<Integer> a=new ArrayList<Integer>();
ArrayList<Integer> b=new ArrayList<Integer>();
      
Collections.addAll(a,1,2,3,4,5,6);
Collections.addAll(b,1,2);
            
a.removeAll(b);
      
System.out.println(a); // will print [3,4,5,6]

An important point: Make sure the element type (Integer in this case) provides a working hashCode and equals implementation.

0
 
avsrivastavaCommented:
Example:

   ArrayList a = new ArrayList(), b = new ArrayList();
   a.add(new Integer(1));
   a.add(new Integer(2));
   a.add(new Integer(3));
   a.add(new Integer(4));
   a.add(new Integer(5));
   b.add(new Integer(2));
   b.add(new Integer(4));
   System.out.println(a.toString()+b.toString());
   a.removeAll(b);
   System.out.println(a.toString()+b.toString());

Output:
[1, 2, 3, 4, 5][2, 4]
[1, 3, 5][2, 4]
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now