w3resource

Java program to check if a list contains a specific word using lambda expression

Java Lambda Program: Exercise-16 with Solution

Write a Java program to implement a lambda expression to check if a list of strings contains a specific word.

Sample Solution:

Java Code:

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

public class Main {
  public static void main(String[] args) {
    // Create a list of strings
    List < String > colors = Arrays.asList("Red", "Green", "Blue", "Orange", "Black");

    // Specify the word to search for
    String searchColor = "Orange";

    // Check if the list contains the specified color using a lambda expression
    Predicate < String > containsWord = word -> word.equals(searchColor);
    boolean flag = colors.stream().anyMatch(containsWord);

    // Print the result
    System.out.println("Is the word " + searchColor + " present in the list? " + flag);

    // Specify the word to search for   
    String searchColor1 = "White";

    // Check if the list contains the specified color using a lambda expression
    Predicate < String > containsWord1 = word -> word.equals(searchColor1);
    flag = colors.stream().anyMatch(containsWord1);

    // Print the result
    System.out.println("\nIs the word " + searchColor1 + " present in the list? " + flag);
  }
}

Sample Output:

Is the word Orange present in the list? true

Is the word White present in the list? false

Explanation:

In the above exercise -

  • Import the necessary classes: Arrays, List, and Predicate.
  • In the main method, we create a list of strings called colors using Arrays.asList().
  • Specify the word we want to search for by assigning it to the variable searchColor.
  • Define a lambda expression to check if a string equals the searchColor using the Predicate functional interface. The lambda expression compares each string with the searchColor using the equals() method.
  • Use the stream() method on the colors list to create a stream of strings.
  • Use the anyMatch() method along with the containsWord predicate to check if any element in the stream matches the predicate.
  • The result of the anyMatch() operation is stored in the boolean variable flag.

Finally, we print the result, indicating whether the list contains the specified color.

Flowchart:

Flowchart: Java  Exercises: Java program to check if a list contains a specific word using lambda expression.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Lambda Exercises Previous: Java program to calculate sum of squares of odd and even numbers using lambda expression.
Java Lambda Exercises Next: Java program to find length of longest and smallest string using lambda expression.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.