如何删除ArrayList中的重复元素

时间:2016-08-27 09:38:30

标签: java android arraylist

我注意到我在listview构建的arrayList中返回了重复的行。我想检查arraylist中是否存在元素,如果存在,则忽略该集合。要检查的唯一值是我的id,由KEY_SID表示。

这是我的代码:

 public ArrayList<SaleModel> loadSalesFromSQLite() {
        ArrayList<SaleModel> sales = new ArrayList<>();
        hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("SELECT  * FROM " + TABLE_SALES + " ORDER BY datetime(created_at) DESC", null);
        res.moveToFirst();
        while (!res.isAfterLast()) {
            SaleModel l_sales = new SaleModel();

            l_sales.setId(res.getString(res
                    .getColumnIndex(KEY_SID)));
            l_sales.setCode(res.getString(res
                    .getColumnIndex(KEY_CODE)));
            l_sales.setAttendant_id(res.getString(res
                    .getColumnIndex(KEY_ATTENDANT_ID)));
            l_sales.setAttendant_name(res.getString(res
                    .getColumnIndex(KEY_ATTENDANT_NAME)));
            l_sales.setProduct_id(res.getString(res
                    .getColumnIndex(KEY_PRODUCT_ID)));
            l_sales.setPrice(res.getString(res
                    .getColumnIndex(KEY_PRICE)));
            l_sales.setCustomer_id(res.getString(res
                    .getColumnIndex(KEY_CUSTOMER_ID)));
            l_sales.setCustomer_first_name(res.getString(res
                    .getColumnIndex(KEY_CUSTOMER_FIRST_NAME)));
            l_sales.setCustomer_last_name(res.getString(res
                    .getColumnIndex(KEY_CUSTOMER_LAST_NAME)));
            l_sales.setCustomer_image(res.getString(res
                    .getColumnIndex(KEY_CUSTOMER_IMAGE)));
            l_sales.setUid(res.getString(res
                    .getColumnIndex(KEY_UID)));
            l_sales.setQuantity(res.getString(res
                    .getColumnIndex(KEY_QUANTITY)));
            l_sales.setP_name(res.getString(res
                    .getColumnIndex(KEY_PRODUCT_NAME)));
            l_sales.setP_image(res.getString(res
                    .getColumnIndex(KEY_PRODUCT_IMAGE)));
            l_sales.setCreated_at(res.getString(res
                    .getColumnIndex(KEY_PRODUCT_CREATED)));
            l_sales.setSvg(res.getString(res
                    .getColumnIndex(KEY_SVG)));
            l_sales.setOfflineTag(res.getString(res
                    .getColumnIndex(KEY_OFFLINETAG)));

            sales.add(l_sales);
            res.moveToNext();
        }
        Log.d(TAG, "Fetching sales from Sqlite: ");
        res.close();
        return sales;
    }

在我返回sales arrayList之前,我想检查那里的重复项,删除它们,返回arrayList没有重复项。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

你可以做几件事:

  1. 在SQL中使用DISTINCTGROUP BY删除从数据库返回的重复项
  2. 将元素添加到Set而不是ArrayList(但您需要确保SaleModel类隐含hashCode()equals()

答案 1 :(得分:0)

使用Lambda Expression

git clone