w3resource

Java generic method: Filter list with predicate

Java Generic: Exercise-6 with Solution

Write a Java program to create a generic method that takes a list of any type and a predicate. It returns an array list containing only elements that satisfy the predicate.

Sample Solution:

Java Code:

// Filter_List_elements.java
// Filter_List_elements Class

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Filter_List_elements {

  public static < T > List < T > filterList(List < T > originalList, Predicate < T > predicate) {
    List < T > filteredList = new ArrayList < > ();

    for (T element: originalList) {
      if (predicate.test(element)) {
        filteredList.add(element);
      }
    }

    return filteredList;
  }

  public static void main(String[] args) {
    List < Integer > numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
    System.out.println("Original list of numbers: " + numbers);
    // Filter even numbers
    List < Integer > evenNumbers = filterList(numbers, n -> n % 2 == 0);
    System.out.println("Even numbers: " + evenNumbers);

    // Filter odd numbers
    List < Integer > oddNumbers = filterList(numbers, n -> n % 2 != 0);
    System.out.println("Odd numbers: " + oddNumbers);

    List < String > colors = List.of("Red", "Green", "White", "Orange", "Black", "Pink");
    System.out.println("\nOriginal list of Colors: " + colors);
    // Filter colors starting with 'O'
    List < String > wordsStartingWithO = filterList(colors, color -> color.startsWith("O"));
    System.out.println("Colors starting with 'O': " + wordsStartingWithO);

    // Filter colors with length greater than 4
    List < String > wordsLengthGreaterThan4 = filterList(colors, color -> color.length() > 4);
    System.out.println("Colors with length greater than 4: " + wordsLengthGreaterThan4);
  }
}

Sample Output:

 Original list of numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Even numbers: [2, 4, 6, 8, 10, 12]
Odd numbers: [1, 3, 5, 7, 9, 11]

Original list of Colors: [Red, Green, White, Orange, Black, Pink]
Colors starting with 'O': [Orange]
Colors with length greater than 4: [Green, White, Orange, Black]

Explanation:

In the above exercise, we define a generic method filterList() that takes a list originalList and a predicate "predicate" as input. The method creates a newly filteredList from an ArrayList. It iterates over the originalList using an enhanced for loop. It applies the predicate to each element using the test() method of the Predicate interface. Using the add() method, the element is added to the filteredList if it meets the predicate.

The method returns the filteredList at the end.

In the main() method, we demonstrate the filterList() method by passing a list of integers (numbers) and a list of strings (words). By applying different predicates, we filter elements from the lists and print the filtered lists.

Flowchart:

Flowchart: Java generic method: Filter list with predicate.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Merge two lists alternately.
Next: Print key-value pairs in a map.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/generic/java-generic-exercise-6.php