简体   繁体   中英

comparision of arraylist

hi am storing the results in array list which are obtained by querying different database in java. i need to compare this array list to get the common rows

      List name = new  ArrayList();
      name.add(Spreadsheets.getString("Name"));

     List namedb = new  ArrayList();
     namedb .add(rs.getString("eName"))

in c++ we use strcmp to compare. but in java how do i compare this arraylist and it should return common rows. or how do i apply binary search algorithm to search these to arraylist?

Use the List's retainAll method.

List<String> names = new ArrayList<String>();
List<String> namesDB =  new ArrayList<String>();

// Get some names ??
names.add(Spreadsheets.getString("Name"));

boolean hasCommonNames =  namesDB.retainAll( names );

// The namesDB will only contain the common names.
if( hasCommonNames ) {
    // Do something with the common names
} 

您可以使用HashMap来存储第一组结果,然后迭代第二个列表,在迭代过程中检查该值是否存在于HashMap中(如果存在),在迭代结束时将其推入另一个List C中,清单C将具有共同的元素

ArrayList<Integer> a3 = new ArrayList<Integer>();               
for (String a : a1)
    a3.add(a2.contains(a) ? 1 : 0);

Now check content of a3. If all is 1, two list are same...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM