File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

To compare 2 list and obtain the unmatched values from the list

 
kannan coding
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 list.

for example, list1 has [2,14]
list2 has [2,8,34,7,14,6]

Now need the output as follows [8,34,7,6]

i.e to remove the values of list1 from list2.
Kindly help me to solve this.
 
Henry Wong
author
Marshal
Pie
Posts: 20823
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kannan:
I have 2 list.

for example, list1 has [2,14]
list2 has [2,8,34,7,14,6]

Now need the output as follows [8,34,7,6]

i.e to remove the values of list1 from list2.
Kindly help me to solve this.


Take a look at the removeAll() method of the List class...

Henry
 
kannan coding
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get the solutions as follows:
package com;

import java.util.*;
public class sample2 {
public static void main(String[] args){
ArrayList ar1 = new ArrayList();
ar1.add("1");
ar1.add("13");
ar1.add("16");
ArrayList ar2 = new ArrayList();
ar2.add("16");
ar2.add("5");
ar2.add("1");
ar2.add("13");
ar2.add("7");
ar2.add("9");
ArrayList ar3 = new ArrayList();
ar3.add("16");
ar3.add("5");
ar3.add("1");
ar3.add("13");
ar3.add("7");
ar3.add("9");
System.out.println("List 1: " + ar1);
System.out.println("List 2: " + ar2);
System.out.println("List 3: " + ar3);

Iterator itr1 = ar1.iterator();
Iterator itr2 = ar2.iterator();

while(itr1.hasNext()){
String id1 = (String)itr1.next();
while(itr2.hasNext()){
String id2 = (String)itr2.next();

if(id1!=null && id2!=null){
if(!id1.equals(id2)){
ar3.remove(id1);
}
}
}
itr2 = ar2.iterator();
}
System.out.println("Final list:" + ar3);
}
}

Kindly Provide me a better solution.
 
kannan coding
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply

i used removeAll() and got the result

list1.removeAll(list2) worked out thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic