Find in list where java

Java Collections Utility Examples for Searching in a Collection

In this Java tutorial, you will learn how to use the Collections utility class in the Java Collections framework to search for elements in a collection.

You know, the java.util.Collections class provides reusable functionalities that operation on collections such as finding extremes values in a collection and searching for specific values in a list. These are grouped into “generic algorithms” category. In this article, we help you understand how to use these functionalities with code examples.

1. Finding extreme values in a collection

The methods in this group allow us to find the maximum and minimum elements in a collection, in terms of natural ordering or using a specified comparator.

Finding the maximum element:

The following method returns the maximum element in a given collection, according to the natural ordering of its elements, which must implement the Comparable interface:

public static T max(Collection collection)

List listNumbers = Arrays.asList(31, 87, 22, 45, 12, 98, 3, 6, 7); Integer max = Collections.max(listNumbers); System.out.println("Maximum number: " + max);

The following overload method returns the maximum element of the given collection, according to the order determined by the specified comparator:

public static T max(Collection coll, Comparator comp)

List listCities = Arrays.asList("London", "Paris", "New York", "Washington", "Tokyo", "Rio De Janero", "Bangalore"); Comparator comparator = new Comparator() < public int compare(String s1, String s2) < return s1.length() - s2.length(); >>; String max = Collections.max(listCities, comparator); System.out.println("Most-letter city name: " + max);
Most-letter city name: Rio De Janero

Finding the minimum element:

The following method returns the minimum element in a given collection, according to the natural ordering of its elements, which must implement the Comparable interface:

public static T min(Collection collection)

List listNumbers = Arrays.asList(31, 87, 22, 45, 12, 98, 3, 6, 7); Integer min = Collections.min(listNumbers); System.out.println("Minimum number: " + min);

The following overload method returns the minimum element of the given collection, according to the order determined by the specified comparator:

Читайте также:  Html link background size

public static T min(Collection coll, Comparator comp)

class Employee implements Comparable  < int salary; String name; public Employee(String name) < this.name = name; >public Employee(int salary) < this.salary = salary; >public Employee(String name, int salary) < this.name = name; this.salary = salary; >public String toString() < return this.name + " (salary: " + salary + ")"; >public int compareTo(Employee another) < return this.name.compareTo(another.name); >>

Here, the natural ordering of the Employee class is based on its name. Hence the following code finds the employee who gets paid the least:

List listEmployees = new ArrayList<>(); listEmployees.add(new Employee("Tom", 40000)); listEmployees.add(new Employee("Adam", 60000)); listEmployees.add(new Employee("Jim", 70000)); listEmployees.add(new Employee("Dane", 35000)); listEmployees.add(new Employee("Jack", 56000)); listEmployees.add(new Employee("Carol", 67000)); Comparator comparator = new Comparator() < public int compare(Employee emp1, Employee emp2) < return this.name.compareTo(another.name); >>; Employee min = Collections.min(listEmployees, comparator); System.out.println("Least paid employee: " + min);
Least paid employee: Dane (salary: 35000)

2. Finding specific values in a list

The methods in this group allow us to search for a specific object in a list, or the position of a list contained within another list.

Binary search according to natural ordering:

The following method searches the specified list for the specified object using the binary search algorithm:

public static int binarySearch(List> list, T key)

Note that the list must be sorted into ascending order according to the natural ordering of its elements before invoking this method. Otherwise the results are undefined.

This method returns the index of the search key if it is contained in the list (in case the list contains multiple elements equal to the specified key, there is no guarantee which one will be found). Also note that the return value always >=0 if and only if the key is found.

The following code example searches for an employee whose name is “Jim” in the list of employees above:

Employee jim = new Employee(«Jim»); Collections.sort(listEmployees); int index = Collections.binarySearch(listEmployees, jim); if (index >= 0)

Found employee: Jim (salary: 70000)

Binary search using a comparator:

The Collections utility class also provides an overloaded method that searches the specified list for the specified object according to the order determined by the specified comparator:

public static int binarySearch(List list, T key, Comparator c)

Note that the list must be sorted into ascending order according to the specified comparator. Otherwise the results are undefined.

For example, the following code searches for an employees who salary is 70,000:

Comparator comparator = new Comparator() < public int compare(Employee emp1, Employee emp2) < return emp1.salary - emp2.salary; >>; Collections.sort(listEmployees, comparator); Employee keyEmp = new Employee(70000); int index = Collections.binarySearch(listEmployees, keyEmp, comparator); if (index >= 0)

Search where a list contained in another:

The following method returns the starting position of the first occurrence of the specified target list within the specified source list:

Читайте также:  Гибрид удава и питона

public static int indexOfSubList(List source, List target)

List source = Arrays.asList(91, 92, 93, 92, 95, 96, 97, 98, 99); List target = Arrays.asList(95, 96, 97); int startingIndex = Collections.indexOfSubList(source, target); System.out.println("Starting position: " + startingIndex);

Search the last position of the target list within the source list:

The following method returns the starting position of the last occurrence of the specified target list within the specified source list (or return -1 if the is no such occurrence):

public static int lastIndexOfSubList(List source, List target)

List source = Arrays.asList(18, 33, 66, 99, 22, 33, 66, 11, 100); List target = Arrays.asList(33, 66); int lastIndex = Collections.lastIndexOfSubList(source, target); System.out.println("Last index : " + lastIndex);

References:

Other Java Collections Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Как найти элемент в списке с помощью 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 не существует.

Читайте также:  Python redis list keys

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.

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

Источник

Оцените статью