Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arraylist - how to get a specific element/name? [closed]

Tags:

java

arraylist

I've tried to search the WWW but failed to find an answer. Couldn't find one here either.

Here's my question: How do I get a specific name(element?) from a Customer in an ArrayList? I'm imagining it looks something like this:

ArrayList<Customer> list = new ArrayList();

String name = list.get(2) // which would return the Customer at 2's place. 

But what if I want to search for a customer by name, lets say a customer named Alex? How do I do that?

Bonus question: How do I then delete that customer?

like image 930
Adem Ökmen Avatar asked Oct 20 '25 02:10

Adem Ökmen


1 Answers

As others have said this isn't all that efficient and a HashMap will give you fast lookup. But if you must iterate over the list you would do it like this:

    String targetName = "Jane";
    Customer result = null;
    for (Customer c : list) {
        if (targetName.equals(c.getName())) {
            result = c;
            break;
        }
    }

If you need to remove an item from a list while iterating over it you need to use an iterator.

    String targetName = "Jane";
    List<Customer> list = new ArrayList<Customer>();
    Iterator<Customer> iter = list.iterator();
    while (iter.hasNext()) {
        Customer c = iter.next();
        if (targetName.equals(c.getName())) {
            iter.remove();
            break;
        }
    }
like image 86
bhspencer Avatar answered Oct 22 '25 15:10

bhspencer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!