amal
amal

Reputation: 3580

Compare content of the ArrayList against Resultset

I have String ArrayList to compare against Resultset.

Ex: ArrayList Elements

ITM001
ITM002
ITM003
ITM004

Ex: Resultset 1

ITM001
ITM002
ITM003
ITM004  

Contains all elements
return ArrayList Empty;

Ex: Resultset 2

ITM001
ITM002
ITM004  

Missing ITM003
return ArrayList ITM003;

Ex: Resultset 3

ITM001
ITM002 

Missing ITM003, ITM004
return ArrayList ITM003,ITM004;

If Resultset does not contain all elements of Arraylist, those missing elements must return as an ArrayList. Else return empty ArrayList.

This is what I tried.

public static ArrayList<String> checkStoreItems(String currentStore, ArrayList<String> stlist) throws ClassNotFoundException, SQLException {
        Connection conn = DBConnection.conn();
        String sql = "select itemId from Store_Items where storeID=(select storeID from StoreMain where locationName=?)";
        Object []values ={currentStore}; 
        ResultSet res = DBHandller.getData(sql, conn, values);
        ArrayList<String> storelist = new ArrayList<String>();
        while(res.next()){
              String item = res.getString("itemId");
              for (int i = 0; i < stlist.size(); i++) {
                    if (item.contains(stlist.get(i))) {
                          continue;     
                    }else{
                          storelist.add(item);
                    }
              }

        }

        return null;

  }

Upvotes: 1

Views: 2415

Answers (2)

AllTooSir
AllTooSir

Reputation: 49352

If I understood your question correctly , you can try something like this :

    public static ArrayList<String> checkStoreItems(String currentStore, 
                       ArrayList<String> stlist) throws ClassNotFoundException, SQLException {
    Connection conn = DBConnection.conn();
    String sql = "select itemId from Store_Items where storeID=(select storeID from StoreMain where locationName=?)";
    Object []values = {currentStore}; 
    ResultSet res = DBHandller.getData(sql, conn, values);
    Set<String> storelist = new HashSet<String>();
    while(res.next()){
          String item = res.getString("itemId");
          storelist.add(item);
   }
    stlist.removeAll(storelist);
    return stlist;
 }

Upvotes: 5

Brigham
Brigham

Reputation: 14524

Use HashSet's removeAll method to perform the operation. You will first need to put the elements from each source into a HashSet.

This avoids the need to loop over the entire ArrayList for every element in the ResultSet making it an O(n) operation, instead of O(n^2).

ArrayList<String> diffResultSet(Collection<String> coll, ResultSet resultSet, int column) {
    Set<String> collSet = new HashSet<String>(coll);
    Set<String> resultSetSet = new HashSet<String>();
    while (resultSet.next()) {
        resultSetSet.add(resultSet.getString(column));
    }
    collSet.removeAll(resultSetSet);
    return new ArrayList<String>(collSet);
}

Upvotes: 1

Related Questions