繁体   English   中英

检查 ArrayList 中是否存在值

[英]Check if a value exists in 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();

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

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

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

在检查值是否存在时,使用HashSet比使用ArrayList更好。

HashSet的 Java 文档说

此类为基本操作(添加、删除、包含和大小)提供恒定的时间性能

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

如果我们提供了equalshashCode的实现,我们可以使用contains方法检查项目是否存在,否则将使用对象引用进行相等比较。 同样,如果列表containsO(n)操作,而HashSetO(1) ,所以以后使用更好。 在 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

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

无需遍历List 只需覆盖equals方法并使用.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;
}

像这样称呼它:

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

}

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

当数组列表包含原始数据类型的对象时。

Use this function:
arrayList.contains(value);

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

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

Follow this below Link 

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

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

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

下面的代码可以帮助

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

ArrayList 已经具有相同的名称,因此它返回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);
    }
}

使用 .contains 将值与

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM