Find item in list java

Find element in list

This example will find the first element in a arraylist that satisfies a given predicate using java, java 8, guava and apache commons.

Straight up Java

Iterating over the collection using a standard for loop an if statement will check for matching element of 3. If a match is found, then the value variable will be set.

@Test public void find_elements_in_list_with_java ()  List Integer> numbers = Lists.newArrayList( new Integer(1), new Integer(2), new Integer(3)); Integer value = null; for (Integer number : numbers)  if (number == 3)  value = number; > > assertEquals(new Integer(3), value); >

Java 8

Using Java 8 this snippet will find the first element in an array list. Java 8 Streams API contains Stream.Filter which will return elements that match a predicate. By passing a java predicate via a lambda expression, the stream will filter any elements that match a value of 3. If any elements match the Stream.findFirst will return an java Optional that describes the element. If no elements match an empty optional will be returned.

@Test public void find_elements_in_list_with_java8_lambda ()  List Integer> numbers = Lists.newArrayList( new Integer(1), new Integer(2), new Integer(3)); OptionalInteger> value = numbers .stream() .filter(a -> a == 3) .findFirst(); assertEquals(new Integer(3), value.get()); >

Google Guava

This snippet will show how to find the first element in an arraylist using guava. Guava’s Iterables.find will return the first element that matches the supplied guava predicate equaling 3.

@Test public void find_elements_in_lists_with_guava ()  List Integer> numbers = Lists.newArrayList( new Integer(1), new Integer(2), new Integer(3)); Integer value = Iterables.find(numbers, new PredicateInteger> ()  public boolean apply(Integer number)  return number == 3 ; > >); assertEquals(new Integer(3), value); >

Apache Commons

Similar to the examples above, this snippet will use apache commons to find the first element in a collection by passing a apache predicate to CollectionUtils.find method.

@Test public void find_elements_in_list_with_apachecommons ()  List Integer> numbers = Lists.newArrayList( new Integer(1), new Integer(2), new Integer(3)); Integer value = (Integer) CollectionUtils.find(numbers, new org.apache.commons.collections.Predicate()  public boolean evaluate(Object number)  return ((Integer)number).intValue() == 3 ; > >); assertEquals(new Integer(3), value); >

Find element in list posted by Justin Musgrove on 13 March 2013

Tagged: java and java-collections

Источник

How to find an element in a List with Java?

The List interface extends Collection interface and represents a collection storing a sequence of elements. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable. ArrayList is the most popular implementation of the List interface among the Java developers.

In Java List, there are couple of ways to find an element.

  • Use indexOf() method. — This method returns the index of the element if present otherwise -1.
  • Use contains() method. — This methods returns true if element is present otherwise false.
  • Loop through the elements of a list and check if element is the required one or not.
  • Loop through the elements of a list using stream and filter out the element.

In this article, we’re going to cover each of the above methods mentioned in examples.

Example 1

Following is an example showing the usage of indexOf() and contains() methods to find an element in a list −

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(); list.add("Zara"); list.add("Mahnaz"); list.add("Ayan"); System.out.println("List: " + list); String student = "Ayan"; if(list.indexOf(student) != -1) < System.out.println("Ayan is present."); >if(list.contains(student)) < System.out.println("Ayan is present."); >> >

Output

This will produce the following result −

List: [Zara, Mahnaz, Ayan] Ayan is present. Ayan is present.

Example 2

Following is an example showing the usage of iteration and streams to find an element in a list −

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(); list.add("Zara"); list.add("Mahnaz"); list.add("Ayan"); System.out.println("List: " + list); String student = "Ayan"; for (String student1 : list) < if(student1 == "Ayan") < System.out.println("Ayan is present."); >> String student2 = list.stream().filter(s -> ).findAny().orElse(null); System.out.println(student2); > >

Output

This will produce the following result −

List: [Zara, Mahnaz, Ayan] Ayan is present. Ayan

Источник

How do I find an element in Java List?

There are couple of ways to find elements in a Java List.

  • Use indexOf() method.
  • Use contains() method.
  • Loop through the elements of a list and check if element is the required one or not.
  • Loop through the elements of a list using stream and filter out the element.

Example

Following is the example showing various methods to find an element −

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(); list.add(new Student(1, "Zara")); list.add(new Student(2, "Mahnaz")); list.add(new Student(3, "Ayan")); System.out.println("List: " + list); Student student = new Student(3, "Ayan"); for (Student student1 : list) < if(student1.getId() == 3 && student.getName().equals("Ayan")) < System.out.println("Ayan is present."); >> Student student2 = list.stream().filter(s -> ).findAny().orElse(null); System.out.println(student2); > > class Student < private int id; private String name; public Student(int id, String name) < this.id = id; this.name = name; >public int getId() < return id; >public void setId(int id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >@Override public boolean equals(Object obj) < if(!(obj instanceof Student)) < return false; >Student student = (Student)obj; return this.id == student.getId() && this.name.equals(student.getName()); > @Override public String toString() < return "[" + this.id + "," + this.name + "]"; >>

Output

This will produce the following result −

List: [[1,Zara], [2,Mahnaz], [3,Ayan]] Ayan is present. [3,Ayan]

Источник

Как найти элемент в списке с помощью Java

Поиск элемента в списке-очень распространенная задача, с которой мы сталкиваемся как разработчики.

В этом кратком руководстве мы рассмотрим различные способы, которыми мы можем сделать это с помощью Java.

Дальнейшее чтение:

Проверка Сортировки списка в Java

Инициализация списка Java в одной строке

2. Настройка

Сначала давайте начнем с определения Customer POJO:

List customers = new ArrayList<>(); customers.add(new Customer(1, "Jack")); customers.add(new Customer(2, "James")); customers.add(new Customer(3, "Kelly")); 

Обратите внимание, что мы переопределили hashCode и equals в нашем классе Customer .

Исходя из нашей текущей реализации equals , два Customer объекта с одинаковым id будут считаться равными.

Мы будем использовать этот список клиентов по пути.

3. Использование Java API

Сама Java предоставляет несколько способов поиска элемента в списке:

3.1. содержит()

List предоставляет метод с именем содержит :

boolean contains(Object element)

Как следует из названия, этот метод возвращает true , если список содержит указанный элемент, и возвращает false в противном случае.

Поэтому, когда нам нужно проверить, существует ли конкретный элемент в нашем списке, мы можем:

Customer james = new Customer(2, "James"); if (customers.contains(james)) < // . >

3.2. Индекс()

indexOf – еще один полезный метод поиска элементов:

int indexOf(Object element)

Этот метод возвращает индекс первого вхождения указанного элемента в данный список или -1, если список не содержит элемента .

Таким образом, логически, если этот метод возвращает что-либо, кроме -1, мы знаем, что список содержит элемент:

if(customers.indexOf(james) != -1) < // . >

Главное преимущество использования этого метода заключается в том, что он может сообщить нам положение указанного элемента в данном списке.

3.3. Основные циклы

А что, если мы хотим выполнить поиск элемента на основе полей? Например, скажем, мы объявляем лотерею, и нам нужно объявить Клиента с определенным именем победителем.

Для таких полевых поисков мы можем обратиться к итерации.

Традиционный способ итерации по списку-использовать одну из циклических конструкций Java. На каждой итерации мы сравниваем текущий элемент в списке с элементом, который мы ищем, чтобы увидеть, соответствует ли он:

public Customer findUsingEnhancedForLoop( String name, List customers) < for (Customer customer : customers) < if (customer.getName().equals(name)) < return customer; >> return null; >

Здесь имя относится к имени, которое мы ищем в данном списке клиентов . Этот метод возвращает первый Customer объект в списке с соответствующим именем или null , если такого Customer не существует.

3.4. Цикл С итератором

Итератор – это еще один способ обхода списка элементов.

Мы можем просто взять наш предыдущий пример и немного подправить его:

public Customer findUsingIterator( String name, List customers) < Iteratoriterator = customers.iterator(); while (iterator.hasNext()) < Customer customer = iterator.next(); if (customer.getName().equals(name)) < return customer; >> return null; >

Следовательно, поведение остается таким же, как и раньше.

3.5. Java 8 Stream API

Начиная с Java 8, мы также можем использовать Stream API для поиска элемента в списке .

Чтобы найти элемент, соответствующий определенным критериям в данном списке, мы:

  • вызовите stream() в списке
  • вызовите метод filter() с соответствующим предикатом
  • вызовите конструкцию find Any () , которая возвращает первый элемент, соответствующий предикатуfilter, завернутому вOptional , если такой элемент существует
Customer james = customers.stream() .filter(customer -> "James".equals(customer.getName())) .findAny() .orElse(null);

Для удобства мы по умолчанию используем значение null в случае, если Необязательный пуст, но это не всегда может быть лучшим выбором для каждого сценария.

4. Сторонние Библиотеки

Теперь, хотя Stream API более чем достаточен, что нам делать, если мы застряли на более ранней версии Java?

К счастью, есть много сторонних библиотек, таких как Google Guava и Apache Commons, которые мы можем использовать.

4.1. Google Guava

Google Guava предоставляет функциональность, похожую на то, что мы можем сделать с потоками:

Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).orNull();

Как и в случае с Stream API, мы можем дополнительно выбрать возврат значения по умолчанию вместо null :

Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).or(customers.get(0));

Приведенный выше код выберет первый элемент в списке, если совпадение не будет найдено.

Кроме того, не забывайте, что Гуава бросает Исключение NullPointerException если либо список, либо предикат нулевой .

4.2. Apache Commons

Мы можем найти элемент почти точно таким же образом, используя Apache Commons:

Customer james = IterableUtils.find(customers, new Predicate() < public boolean evaluate(Customer customer) < return "James".equals(customer.getName()); >>);

Однако есть несколько важных отличий:

  1. Apache Commons просто возвращает null , если мы передаем список null .
  2. Ононе обеспечивает функциональность значений по умолчанию, как у Guavaпопробуй Найти.

5. Заключение

В этой статье мы изучили различные способы поиска элемента в списке , начиная с быстрых проверок существования и заканчивая полевыми поисками.

Мы также рассмотрели сторонние библиотеки Google Guava и Apache Commons как альтернативы Java 8 Streams API.

Спасибо, что заглянули, и не забудьте проверить все источники для этих примеров на GitHub.

Читайте ещё по теме:

Источник

Читайте также:  Javascript html style width
Оцените статью