在集合中查找单个对象,HashMap vs List过滤器

Loc*_*oci 7 java java-8 java-stream

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);
Run Code Online (Sandbox Code Playgroud)

使用Java 8方法会有性能提升吗?这些方法之间的最佳实践是什么?

Era*_*ran 12

在HashMap中按键搜索值需要O(1)预期时间,这比在List中搜索相同值所需的O(n)要快.

使用Java 8 Streams并没有改变这一点,因为在花哨的新语法的幕后,它仍然遍历List的元素,直到找到匹配.

  • "O(1)预期时间"是没有意义的,因为O(1)不是时间单位,而"比O(n)更快"只是*错*.正确的说法是,对于"*n*的大值",O(1)*的时间复杂度比O(n)更好地缩放*.但是,使用流API执行线性搜索的结论是没有改进仍然是正确的.不仅因为它不能很好地扩展大*n*s,而且因为`.get(customerId)`比`.stream()更易读.过滤器(c - > c.customerId == id).findAny ()获得()`. (2认同)