Java Collections Utility Examples for Searching in a Collection
- Details
- Written by Nam Ha Minh
- Last Updated on 11 April 2024   |   Print Email
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.
- Collections.max() examples
- Collections.min() examples
- Collections.binarySearch() examples
- Collections.indexOfSubList() example
- Collections.lastIndexOfSubList() example
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<? extends T> collection)
Code example:
List<Integer> listNumbers = Arrays.asList(31, 87, 22, 45, 12, 98, 3, 6, 7); Integer max = Collections.max(listNumbers); System.out.println("Maximum number: " + max);
Output:
Maximum number: 98
The following overload method returns the maximum element of the given collection, according to the order determined by the specified comparator:
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
The following code example finds in a list of Strings the String having the most number of letters:
List<String> listCities = Arrays.asList("London", "Paris", "New York", "Washington", "Tokyo", "Rio De Janero", "Bangalore"); Comparator<String> comparator = new Comparator<String>() { 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);
Output:
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<? extends T> collection)
Code example:
List<Integer> listNumbers = Arrays.asList(31, 87, 22, 45, 12, 98, 3, 6, 7); Integer min = Collections.min(listNumbers); System.out.println("Minimum number: " + min);
Output:
Minimum number: 3
The following overload method returns the minimum element of the given collection, according to the order determined by the specified comparator:
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
Given the following entity class:
class Employee implements Comparable<Employee> { 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 Employeeclass is based on its name. Hence the following code finds the employee who gets paid the least:
List<Employee> 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<Employee> comparator = new Comparator<Employee>() { 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);
Output:
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 <T> int binarySearch(List<? extends Comparable<? super T>> 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) { jim = listEmployees.get(index); System.out.println("Found employee: " + jim); }
Output:
Found employee: Jim (salary: 70000)
Binary search using a comparator:
The Collectionsutility 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 <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> 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<Employee> comparator = new Comparator<Employee>() { 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) { keyEmp = listEmployees.get(index); System.out.println("Found: " + keyEmp); }
Output:
Found: Jim (salary: 70000)
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)
This method returns -1 if the target list is not contained in the source list. Here’s an example:
List<Integer> source = Arrays.asList(91, 92, 93, 92, 95, 96, 97, 98, 99); List<Integer> target = Arrays.asList(95, 96, 97); int startingIndex = Collections.indexOfSubList(source, target); System.out.println("Starting position: " + startingIndex);
Output:
Starting position: 4
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)
Code example:
List<Integer> source = Arrays.asList(18, 33, 66, 99, 22, 33, 66, 11, 100); List<Integer> target = Arrays.asList(33, 66); int lastIndex = Collections.lastIndexOfSubList(source, target); System.out.println("Last index : " + lastIndex);
Output:
Last index : 5
References:
Related Collection Utility Classes Tutorials:
- Java Arrays Utility Class Examples for List view, Sorting and Searching
- Java Collections Factory Method Examples
- Java Collections Utility Examples for Changing Order and Content of a List
- Java Collections Wrapper Methods Examples
Other Java Collections Tutorials:
- What is Java Collections Framework?
- Java Queue Tutorial
- Java List Tutorial
- Java Set Tutorial
- Java Map Tutorial
- Understand equals and hashCode
- Understand object ordering
- 18 Java Collections and Generics Best Practices
Comments
Digital marketing course in Hyderabad