簡體   English   中英

我應該使用哪個集合來檢查值是否在100K元素的集合中?

[英]Which collection should I use to check if a value is in the collection of 100K elements?

我是Java的新手,我不知道java集合實現之間的區別。

我必須處理多達100K的導入數據記錄。 該列表可能有重復項。 我必須把所有這些都放到DB中。 在導入之前我清理數據庫表,因此在開頭的DB中沒有重復項。

使用hibernate插入數據的批處理。 我想做這樣的事情:

SomeCollectionClass<Integer> alreadyInsertedRecords;
//...
if (!alreadyInsertedRecords.contains(currentRecord.hashCode()) {
    save_to_database(currentRecord);
    alreadyInsertedRecords.put(currentRecord.hashCode());
} else {
    logger.log("Record no 1234 is a duplicate, skipping");
}

我應該使用哪個集合類來檢查記錄是否已插入到數據庫中?

正如我所說,可能有超過10萬條記錄,因此集合應該快速搜索,快速插入並具有較小的內存占用。

您可以嘗試使用HashSet 請記住,包含的對象的類必須正確實現方法hashCode()和equals()。

如果條目是可排序的,則可以使用TreeSet集合,該集合將自動修剪所有重復條目,前提是它們具有有效的compareTo()equals()方法。

此集合還provides guaranteed log(n) time cost for the basic operations (add, remove and contains). [參考]

如果您有權訪問hashCode()函數,則可以使用HashSet 它的工作方式與TreeSet(插入時的剪枝)相似,而且速度更快。

Colsult Hashset與Treeset問題有關這兩個集合的詳細信息。

如果可能,請使用HashSet

如果您不想復制,可以使用

Set<Integer> alreadyInsertedRecords = new HashSet<Integer>()

我不會為此使用集合,因為它可以在數據庫級別完成。 您可以使用insert not not exists語句。

例如

insert into people (firstName, lastName) 
select 'Foo', 'Bar'
where not exists (
    select 1 from people where firstName = 'Foo' and lastName = 'Bar'
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM