Java 检查 ArrayList 中是否存在值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4404084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:04:23  来源:igfitidea点击:

Check if a value exists in ArrayList

javaarraylistcontains

提问by daniel__

How can I check if a value that is written in scanner exists in an ArrayList?

如何检查写入扫描仪的值是否存在于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();

采纳答案by GreenMatt

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

只需使用ArrayList.contains(desiredElement)。例如,如果您要从示例中查找 conta1 帐户,则可以使用以下内容:

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 CurrentAccountobject and the selecting Source > Generate hashCode() and equals()...

编辑:请注意,为了使其正常工作,您需要正确覆盖equals()hashCode()方法。如果您使用的是 Eclipse IDE,那么您可以通过首先打开CurrentAccount对象的源文件并选择Source > Generate hashCode() and equals()...

回答by SBA

Better to use a HashSetthan an ArrayListwhen you are checking for existence of a value. Java docs for HashSetsays: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

在检查值是否存在时,使用 aHashSet比使用an更好ArrayList。Java 文档HashSet说:"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.

ArrayList.contains()可能必须遍历整个列表才能找到您要查找的实例。

回答by Sameer Kazi

Please refer to my answer on this post.

请参考我在这篇文章中的回答。

There is no need to iterate over the Listjust overwrite the equalsmethod.

无需迭代List刚刚覆盖的equals方法。

Use equalsinstead of ==

使用equals代替==

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

}

回答by Aman Goyal

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.

当数组列表包含 UserDefined DataType 的对象时。

Follow this below Link 

How to compare Objects attributes in an ArrayList?

如何比较 ArrayList 中的对象属性?

I hope this solution will help you. Thanks

我希望这个解决方案能帮助你。谢谢

回答by Prasanth R i-loads Testing Eng

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");         
        }
    } 
}

回答by codingpower472

Just use .contains. For example, if you were checking if an ArrayList arrcontains 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 docsfor .contains.

只需使用.contains. 例如,如果您要检查 ArrayList 是否arr包含 value val,您只需运行arr.contains(val),它将返回一个布尔值,表示是否包含该值。欲了解更多信息,请参阅文档.contains

回答by akhil_mittal

We can use containsmethod to check if an item exists if we have provided the implementation of equalsand hashCodeelse object reference will be used for equality comparison. Also in case of a list containsis O(n)operation where as it is O(1)for HashSetso 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.

contains如果我们提供了 的实现,我们可以使用方法来检查项目是否存在equalshashCode否则将使用对象引用进行相等比较。此外,在列表中的情况containsO(n)操作,其中,因为它是O(1)HashSet这样更好地以后使用。在 Java 8 中,我们也可以使用流来根据项目的相等性或基于特定的属性来检查项目。

Java 8

爪哇 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