我生成一个列表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 的元素,直到找到匹配项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)