201

How can I check if a value that is written in scanner 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();
bobbyrne01
  • 5,926
  • 14
  • 70
  • 139
daniel__
  • 11,255
  • 14
  • 61
  • 91

8 Answers8

363

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()...

Tim Bender
  • 19,703
  • 2
  • 46
  • 58
GreenMatt
  • 17,688
  • 7
  • 50
  • 76
  • 10
    equals() method should be overridden in CurrentAccount to determinate when they are the same object – Javi Dec 09 '10 at 23:28
  • 3
    In that case hashcode() needs to be overridden, too. Per hashcode() contract equal objects must have equal hashcodes. – zockman Dec 09 '10 at 23:46
  • @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. – Javi Dec 09 '10 at 23:51
  • Is there a version that compares object refferences? – Tomáš Zato - Reinstate Monica Feb 10 '15 at 22:37
  • Hi, Is it possible to check list if it contains "Alberto Carlos"? – Jodi Dec 14 '16 at 20:56
  • @Jackie: Not 100% sure I understand what you're asking. Yes, it should be possible. What have you tried? – GreenMatt Dec 14 '16 at 23:34
  • @GreenMatt I follow your method. but instead of conta1, I used "Alberto Carlos". – Jodi Dec 15 '16 at 14:06
  • @Jackie: Sorry, I was rushed earlier and misunderstood what you were asking. Your search term will have to be the same data type as the elements of the List. If you have a list of account holders and want to search for the account holder's name, I believe you'll have to write your own search. – GreenMatt Dec 15 '16 at 15:54
  • @Jackie: Mistyped above. I should have said that if you have a List of CurrentAccounts and want to search on a name, then you will need to write your own search. It shouldn't be too difficult - basically you'll loop through the List and compare the names. – GreenMatt Dec 15 '16 at 16:47
  • What if I cannot override equals . since object is in another library . Now how can I achieve this? – user1846749 Aug 17 '17 at 05:00
  • @user1846749: That seems like a topic for another question. (Sorry to pass the buck, but I don't program in Java these days.) – GreenMatt Sep 12 '17 at 20:03
  • its not working, however overriding equals method it worked for me. – Hussain KMR Behestee May 08 '18 at 18:57
  • @user1846749 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.) – David Mays May 20 '22 at 18:20
53

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.

Moduo
  • 623
  • 6
  • 17
SBA
  • 559
  • 3
  • 2
18

Please refer to my answer on this post.

There is no need to iterate over the List just overwrite the equals method.

Use equals instead of ==

@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));

}
Sameer Kazi
  • 16,423
  • 2
  • 32
  • 46
18

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
akhil_mittal
  • 21,313
  • 7
  • 90
  • 91
  • 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 ?? – maryem neyli Jun 15 '20 at 12:05
  • 1
    @maryemneyli use `findAny`: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#findAny-- – akhil_mittal Jun 16 '20 at 03:31
  • 1
    Call requires API level 24 (current min is 19): `java.util.Collection#stream` – shirin Jul 04 '20 at 09:47
  • 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 POJO – Radhesh Khanna Dec 16 '20 at 20:02
2

Just use .contains. For example, if you were checking if an ArrayList arr contains a value val, you would simply run arr.contains(val), which would return a boolean representing if the value is contained. For more information, see the docs for .contains.

Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
1

When Array List contains object of Primitive DataType.

Use this function:
arrayList.contains(value);

if list contains that value then it will return true else false.

When Array List contains object of UserDefined DataType.

Follow this below Link 

How to compare Objects attributes in an ArrayList?

I hope this solution will help you. Thanks

Aman Goyal
  • 359
  • 4
  • 8
1
public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}
Matyas
  • 1,006
  • 5
  • 23
  • 27
0

Below code can helps

List<CurrentAccount> lista = new ArrayList<CurrentAccount>();
CurrentAccount conta5 = new CurrentAccount("Pedro Fonseca", 500);
boolean isAdded = lista.contains(model);

ArrayList already have same name so it returns true

import com.google.gson.annotations.SerializedName;    
import java.util.Objects;

public class CurrentAccount {

    @SerializedName("Name")
    private String name;
    
    @SerializedName("Balance")
    private int balance;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public CurrentAccount(String name, int balance) {
        this.name = name;
        this.balance = balance;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CurrentAccount model = (CurrentAccount) o;
        return name.equals(model.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}
Pratik Dodiya
  • 1,559
  • 1
  • 13
  • 10