在集合中查找单个对象,HashMap vs List filter

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 不会改变这一点,因为在花哨的新语法的幕后,它仍然迭代列表的元素,直到找到匹配项。