簡體   English   中英

在集合中查找單個對象,HashMap vs List過濾器

[英]Find a single object in a collection, HashMap vs List filter

我從我讀過的文件中生成了一個Customer列表。 我將這些客戶存儲在HashMap ,其中密鑰是唯一ID:

Map<String, Customer> customers = readCustomers(); //For each object created customers.put(c.getCustomerId(), c);

從第二個文件中,我獲取了用於更新HashMap對象的數據。 我使用密鑰來查找要更新的對象:

//get the details informations customers.get(customerId).setDetails(details);

在java 8中我可以使用:

class Customer{
    ... 

    public static Customer find(List<Customer> customers, int id) {
        return customers.stream().filter(c -> c.customerId == id).findAny().get();
    }
}

//usage
List<Customer> customers = readCustomers();    
...
Customer.find(customers, 21).setDetails(details);

使用Java 8方法會有性能提升嗎? 這些方法之間的最佳實踐是什么?

在HashMap中按鍵搜索值需要O(1)預期時間,這比在List中搜索相同值所需的O(n)快。

使用Java 8 Streams並沒有改變這一點,因為在花哨的新語法的幕后,它仍然遍歷List的元素,直到找到匹配。

暫無
暫無

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

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