java - 在对象中查找值时使用 ArrayList.indexOf
问题描述
我有一个包含客户对象数组列表的分支类。在分支类中,我想addTransaction
为给定的客户名称,但首先我想检查客户是否存在,然后添加交易。
private boolean customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if(customers.get(i).getCustomerName().equalsIgnoreCase(customerName)) {
return true;
}
}
return false;
}
private int customerPosition(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if(customers.get(i).getCustomerName().equalsIgnoreCase(customerName)) {
return i;
}
}
return -1;
}
public void addTransaction(String customerName, Double transactionValue) {
if(customerExists(customerName) == false) {
System.out.println("Customer with name " + customerName + " not found");
} else {
customers.get(customerPosition(customerName)).addTransaction(transactionValue);
}
}
我知道这段代码可以工作,但是我意识到我必须通过 arraylist 进行 2 次循环来检查它是否存在,并获得它的位置。这似乎效率低下
我知道该indexOf
方法addTransaction
在在对象中寻找值。任何建议将不胜感激。
编辑:谢谢大家,这些答案太棒了。
解决方案
一般来说,除了循环遍历列表来查找值之外,您不能做得更好。
在代码重复方面,将正文替换为customerExists
:
return customerPosition() >= 0;
并且,在 中addTransaction()
,将 的结果存储customerPosition()
在一个变量中,并使用thatVariable >= 0
而不是调用customerExists()
.
如果您使用的是 Java 8+,则可以使用流:
Optional<Customer> cust = customers.stream().filter(c -> c.getCustomerName().equals(customerName)).findFirst();
那么你就完全不用担心使用索引了。
推荐阅读
- laravel - 未找到基表或视图:1146 表
- vba - Excel 2013 无法解析 Outlook 收件人
- java - 从表中更新一列并插入新行。SQLite,Java
- gcc - 如何修复“警告 #1173-D:属性“已弃用”被忽略?
- python - Sagemaker 调用端点返回值类型?
- android - ConditionVariable 在 AsyncTask 中不起作用
- ios - 在 ios 11 中的 whatsapp 上共享带有标题的图像
- html - 输入元素的 HTML 模式验证
- excel - 根据另一个单元格的内容将格式应用于单元格的一部分
- php - 如何将 a 标签包裹在 div 标签周围?