首页 > 解决方案 > 在对象中查找值时使用 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在在对象中寻找值。任何建议将不胜感激。

编辑:谢谢大家,这些答案太棒了。

标签: javaarraylistgetter

解决方案


一般来说,除了循环遍历列表来查找值之外,您不能做得更好。

在代码重复方面,将正文替换为customerExists

return customerPosition() >= 0;

并且,在 中addTransaction(),将 的结果存储customerPosition()在一个变量中,并使用thatVariable >= 0而不是调用customerExists().

如果您使用的是 Java 8+,则可以使用流:

Optional<Customer> cust = customers.stream().filter(c -> c.getCustomerName().equals(customerName)).findFirst();

那么你就完全不用担心使用索引了。


推荐阅读