Check if a value exists in ArrayList
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
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()...
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.