0

i have 3 string list called Cname,cnamedb,Pname. These 3 lists has a result obtained by query the SQL database.cname and Pname results are getting from querying excel database. cnamedb result is getting from querying SQL database.

i declared and stored into array like this.

 List Cname = new  ArrayList();
 List Pname =new ArrayList();
 List cnamedb=new  ArrayList();

  Cname.add(rs.getString("Cname"));
  Pname.add(rs.getString("Pname"));
  cnamedb.add(res.getString("Cname"));

i tried like this

        boolean hasCommonName = Cname.retainAll(Cnamedb);
         if(hasCommonName){
          out.println(Cname+"<br>");
         out.println(hasCommonName);
      }
       boolean haspname=Pname.retainAll(Cnamedb);
      if(haspname){
     out.println(haspname);
     }

This is just giving me a answer true for the first if statement but not printing the list elements. for the second if statements no results am getting.

i need to find out common elements exists in database and the excel, first i need to get common elements from Cname and Cnamedb and then from Pname and Cnamedb. how do i get the common elements.please provide me the code snippet.

user1063145
  • 71
  • 2
  • 10
  • 2
    possible duplicate of [Common elements in two lists](http://stackoverflow.com/questions/5943330/common-elements-in-two-lists) Also, it would be a lot easier to do the intersection in SQL instead of java. –  Apr 19 '12 at 08:40
  • please check the code which i have edited. even though using retainAll am not able to print the values. – user1063145 Apr 19 '12 at 08:50
  • Please learn java naming conventions and stick to them. – kleopatra Apr 19 '12 at 10:03

1 Answers1

0

the below given snippet worked for me.

    List<String> commonToCnameAndCnamedb = new ArrayList<String>(Cname);

    List<String> commonToPnameAndCnamedb = new ArrayList<String>(Pname);

    boolean hasCommonName = commonToCnameAndCnamedb.retainAll(cnamedb);
    if (hasCommonName) {
        System.out.println(commonToCnameAndCnamedb + "<br>");
        System.out.println(hasCommonName);
    }
    boolean haspname = commonToPnameAndCnamedb.retainAll(cnamedb);
    if (haspname) {
        System.out.println(commonToPnameAndCnamedb + "<br>");
        System.out.println(haspname);
    }
Shamli
  • 84
  • 5
  • its giving me true true for both if conditions. but its not printing the common elements System.out.println(commonToPnameAndCnamedb + "
    ");
    – user1063145 Apr 19 '12 at 09:48
  • I am also getting true for all the cases. But the common elements are listed properly for me. no idea what is happening there at your end – Shamli Apr 19 '12 at 15:01