Filter a List of Objects Based on a Condition

Filtering Names by Initial Letter in Java

When you have a list of names, filtering out certain entries can be useful for tasks like generating personalized reports or organizing data. In today’s article we will filter a list based on a condition, and for the example, we’ll filter names that begin with the letter “A.”

Initial Solution

Let’s start with a basic solution to filter names beginning with “A”:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

List<String> filteredNames = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());

System.out.println(filteredNames);

We convert the list to a stream, which allows us to perform operations on elements in sequence. We use .filter() to retain only names that start with “A.” and collect(Collectors.toList()) collects the filtered results back into a list.

This results in a list containing only the names that begin with “A,” in this case: ["Alice"].

Result

After running this code, the output is:

[Alice]

Alternative Methods for Filtering

1. Using Enhanced For-Loop (Without Streams)

For those new to streams, here’s a traditional approach that accomplishes the same task:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filteredNames = new ArrayList<>();

for (String name : names) {
    if (name.startsWith("A")) {
        filteredNames.add(name);
    }
}

System.out.println(filteredNames);

This approach loops through each element in names and adds it to filteredNames if it begins with “A.”

  • Pros: Simple and easy for beginners to understand.
  • Cons: More verbose and less concise than using streams.
2. Using Java 8 Streams with Method Reference

Another way to implement this using a method reference:

List<String> filteredNames = names.stream()
    .filter(Filters::startsWithA)
    .collect(Collectors.toList());

System.out.println(filteredNames);

// Method Reference
class Filters {
    static boolean startsWithA(String name) {
        return name.startsWith("A");
    }
}

This uses a custom method startsWithA to improve readability. Using method references can make code more expressive, especially in larger projects.

Performance Considerations

When working with large datasets, consider these optimizations:

  1. Parallel Streams: If you have a large list, a parallel stream may improve performance by processing elements in parallel.
   List<String> filteredNames = names.parallelStream()
       .filter(name -> name.startsWith("A"))
       .collect(Collectors.toList());
  1. Immutable Lists: If your list of names doesn’t need to change, consider using immutable lists to improve safety and reduce memory usage.

Filtering is a powerful tool in Java, whether using streams or traditional loops. The flexibility Java provides lets you tailor your approach to meet your application’s needs.

Filtering complete! Only the names that start with “A” have made it through. As always, keep refining your code and experimenting with different methods to see which works best for your use case.
In this article we have seen how to filter a list of objects based on a condition, and in a previous one we have seen how to split a list based on a predicate , for more tips and tricks, stay tuned to Byte-Code, or subscribe to our newsletter !


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect