Check if a value exists in ArrayList
Asked Answered
D

4

220

How can I check if a value exists in an ArrayList?

List<CurrentAccount> lista = new ArrayList<CurrentAccount>();

CurrentAccount conta1 = new CurrentAccount("Alberto Carlos", 1052);
CurrentAccount conta2 = new CurrentAccount("Pedro Fonseca", 30);
CurrentAccount conta3 = new CurrentAccount("Ricardo Vitor", 1534);
CurrentAccount conta4 = new CurrentAccount("João Lopes", 3135);

lista.add(conta1);
lista.add(conta2);
lista.add(conta3);
lista.add(conta4);

Collections.sort(lista);

System.out.printf("Bank Accounts:" + "%n");
Iterator<CurrentAccount> itr = lista.iterator();
while (itr.hasNext()) {
    CurrentAccount element = itr.next();
    System.out.printf(element + " " + "%n");
}
System.out.println();
Dave answered 9/12, 2010 at 23:11 Comment(0)
A
379

Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...

Angwantibo answered 9/12, 2010 at 23:19 Comment(8)
equals() method should be overridden in CurrentAccount to determinate when they are the same objectArnuad
In that case hashcode() needs to be overridden, too. Per hashcode() contract equal objects must have equal hashcodes.Ponderous
@zockman sure you're right, though I think overriding equals is even more important in this case because if not a CurrentAccount object may not be the same even when all their attributes have the same value. But I do agree in overriding hashcode() too.Arnuad
Is there a version that compares object refferences?Josephus
What if I cannot override equals . since object is in another library . Now how can I achieve this?Thirtytwo
@user1846749: That seems like a topic for another question. (Sorry to pass the buck, but I don't program in Java these days.)Angwantibo
its not working, however overriding equals method it worked for me.Kalie
@Thirtytwo did you find a way to do this without overriding equals? I'm attempting to use it in VBA which also utilizes an ArrayList, but you can't override equals in VBA... (that I know of.)Sedan
A
54

Better to use a HashSet than an ArrayList when you are checking for existence of a value.

Java docs for HashSet says

This class offers constant time performance for the basic operations (add, remove, contains and size)

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

Antetype answered 10/12, 2010 at 4:23 Comment(0)
B
27

We can use contains method to check if an item exists if we have provided the implementation of equals and hashCode else object reference will be used for equality comparison. Also in case of a list contains is O(n) operation where as it is O(1) for HashSet so better to use later. In Java 8 we can use streams also to check item based on its equality or based on a specific property.

Java 8

CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true

String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true
Belita answered 14/8, 2018 at 9:12 Comment(4)
thank you for this amazing answer actually it's a +1 ! I used this part of the code :boolean itemExistsBasedOnProp = selectedR.stream().map(Request::getDesc).anyMatch(cn::equals); now I need it to extract that item! is it possible ??Groin
@maryemneyli use findAny: docs.oracle.com/javase/8/docs/api/java/util/stream/…Belita
Call requires API level 24 (current min is 19): java.util.Collection#streamPisistratus
This Solution also works when we have a List of POJO and we want to check for any value from the set of properties present in the POJOThies
L
18

Please refer to my answer on this post.

There is no need to iterate over the List; just override the equals method and use .contains.

@Override
public boolean equals (Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
        result = false;
    } else {
        EmployeeModel employee = (EmployeeModel) object;
        if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
            result = true;
        }
    }
    return result;
}

Call it like this:

public static void main(String args[]) {

    EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
    EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
    EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);

    List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    employeeList.add(first);
    employeeList.add(second);
    employeeList.add(third);

    EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
    System.out.println("Check checkUserOne is in list or not");
    System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));

    EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
    System.out.println("Check checkUserTwo is in list or not");
    System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));

}
Lynnett answered 20/3, 2014 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.