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的元素,直到找到匹配.
| 归档时间: |
|
| 查看次数: |
1281 次 |
| 最近记录: |