Check if a value exists in ArrayList

后端 未结 7 2596
长发绾君心
长发绾君心 2020-11-27 13:37

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

List lista = new ArrayList

        
7条回答
  •  甜味超标
    2020-11-27 14:06

    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
    

提交回复
热议问题