You can query an ArrayList in Java with get methods to return element by the specified index; indexOf methods to return index by the specified element; contains methods to check existing; size and isEmpty methods to check the ArrayList size

Find / search element by index

  • get(int) method gets the element at the specified index in the list. IndexOutOfBoundsException will be thrown if the specified index is out of range
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.get(0)); // 3  
System.out.println(lst.get(3)); // throws IndexOutOfBoundsException


Find / search index by element

  • indexOf(Object) method returns the index of the first occurrence of the specified element in the list, otherwise returns -1
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.indexOf(3)); // 0  
System.out.println(lst.indexOf(4)); // -1
  • lastIndexOf(Object) method returns the index of the last occurrence of the specified element in the list, otherwise returns -1
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(3);

System.out.println(lst.lastIndexOf(3)); // 2  
System.out.println(lst.lastIndexOf(4)); // -1


Check if elements existing

  • contains(Object) method checks if an ArrayList contains the specified element
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.contains(1)); // true  
  • containsAll(Collection) method checks if an ArrayList contains all of elements in the specified collection
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.containsAll(List.of(1, 3))); // true  
System.out.println(lst.containsAll(List.of(1, 4))); // false  


Check ArrayList size

  • size() gets the number of elements in the list
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.size()); // 3
  • isEmpty() checks if the list contains no elements
List<Integer> lst = new ArrayList<>();  
lst.add(3);  
lst.add(1);  
lst.add(2);

System.out.println(lst.isEmpty()); // false