![](/img/trans.png)
[英]How use stream filter for list of hashmap? ArrayList<HashMap<String, Object>>
[英]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.