When creating an application, performing the operation of finding an element in a Java list is one of the most common tasks. In this article, we will see different approaches using Java’s API and third-party libraries to find a specific element in a list.
If you want more information about ArrayList in Java, you can take a look at this article.
Introduction
One of the most common programming tasks is getting an element from a list. Depending on our needs, we will use one method or another. In this post, we will see how to get an element from a list using the following approaches:
- IndexOf()
- Loop For
- Iterator
- Java Streams
- Guava
- Apache Commons
Finding an element in a List using IndexOf()
To get an element from a list in Java, we use the get(int position) method. But first, we need to know in which position it is located, and for this, the IndexOf() method will be of great help:
int indexOf(Object element)
The IndexOf() method returns the index of the first occurrence of the element passed as a parameter. If the element does not exist, it returns -1.
@Test public void given_a_string_list_when_find_amarillo_then_return_element() { List listA = Arrays.asList("Amarillo", "Rojo", "Azul", "Verde", "Gris"); int index = listA.indexOf("Amarillo"); assertEquals("Amarillo",listA.get(index)); }
Using a For loop to find an element in a List in Java
One of the most traditional ways of performing searches in Java is iterating using a FOR loop. In each iteration, we analyze the element to search. For example, if we have an object with several fields, and we want to search for a specific field:
@ParameterizedTest @ValueSource(strings = {"Pepe"}) public void given_a_name_when_find_name_in_list_then_return_user(String userName) { List<User> users = Arrays.asList( User.builder().name("Pepe").build(), User.builder().name("Josh").build(), User.builder().name("Sarah").build() ); User userFound = null; for (User user : users) { if (user.getName().equalsIgnoreCase(userName)) { userFound = user; return; } } assertEquals(userFound, users.get(0)); }
In the previous example, we have relied on JUnit 5’s ParametizedTest functionality to search for a name.
Using an Iterator to find an element
Like with a for loop, another conventional way of finding an element in a list is by using an iterator.
@ParameterizedTest @ValueSource(strings = {"Pepe"}) public void given_a_name_when_find_name_in_list_with_iterator_then_return_user(String userName) { List<User> users = Arrays.asList( User.builder().name("Pepe").build(), User.builder().name("Josh").build(), User.builder().name("Sarah").build() ); User userFound = null; Iterator<User> iterator = users.iterator(); boolean cont = true; while (iterator.hasNext() && cont) { User user = iterator.next(); if (user.getName().equals(userName)) { userFound = user; cont = false; } } assertEquals(userFound, users.get(0)); }
Using the Java Stream API to find an element in a list
With the release of Java 8, functional programming in Java and the Stream API appeared. Java Streams allow us to find elements in a list using the filter(), findFirst(), and findAny() functions.
Let’s see a solution using findAny():
@ParameterizedTest @ValueSource(strings = {"Pepe"}) public void given_a_name_when_find_name_in_list_with_java_stream_find_any_then_return_user( String userName) { List<User> users = Arrays.asList( User.builder().name("Pepe").build(), User.builder().name("Josh").build(), User.builder().name("Sarah").build() ); User userFound = users.stream() .filter(user -> user.getName().equalsIgnoreCase(userName)) .findAny() .orElseThrow(() -> new IllegalArgumentException()); assertEquals(userFound, users.get(0)); }
And another solution using findFirst():
@ParameterizedTest @ValueSource(strings = {"Sarah"}) public void given_a_name_when_find_name_in_list_with_java_stream_then_return_user( String userName) { List<User> users = Arrays.asList( User.builder().name("Pepe").build(), User.builder().name("Josh").build(), User.builder().name("Sarah").build() ); User userFound = users.stream() .filter(user -> user.getName().equalsIgnoreCase(userName)) .findFirst() .orElseThrow(() -> new IllegalArgumentException()); assertEquals(userFound, users.get(2)); }
It’s important to note that both approaches return an Optional that can be handled in different ways. In this case, we throw an exception.
Using Apache Commons
The Apache Commons library offers us the IterableUtils class, which allows us to get an element from a Java list.
@ParameterizedTest @ValueSource(strings = {"Pepe"}) public void given_a_name_when_find_name_in_list_with_apache_commons_then_return_user( String userName) { List<User> users = Arrays.asList( User.builder().name("Pepe").build(), User.builder().name("Josh").build(), User.builder().name("Sarah").build() ); User userFound = IterableUtils.find(users, user -> userName.equals(user.getName())); assertEquals(userFound, users.get(0)); }
It’s important to note that the Predicate object belongs to org.apache.commons.collections4.Predicate instead of Java.
Using the Google Guava library to find an element
The Google Guava library, in a similar way to Apache Commons, offers us the Iterables class with the tryFind method to find elements in a list.
@ParameterizedTest @ValueSource(strings = {"Pepe"}) public void given_a_name_when_find_name_in_list_with_guava_then_return_user( String userName) { User userFound = Iterables.tryFind(users, user -> userName.equals(user.getName())).get(); assertEquals(userFound, users.get(0)); }
Conclusion
In this post, we have seen the different approaches that we have in Java to find an element in a list. Depending on our needs, we will apply one method or another.
If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!