Write a Java program using Lambda Expression to filter out all strings from a list that have a length greater than 5 characters
The java program that filters a list of strings to retain only those strings with a length less than or equal to 5 characters using Java Streams and a lambda expression. Here's an explanation of the code:
- import java.util.ArrayList;: This line imports the ArrayList class from the java.util package, which is used to create a list of strings.
- import java.util.Arrays;: This line imports the Arrays class from the java.util package, which is used to create a list of strings from an array.
- The GreaterFiveChar class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig");: This line creates a list of strings named strings and initializes it with a list of strings.
- System.out.println("Given String : " + strings);: This line prints the original list of strings.
- The program uses a Java Stream to filter the strings based on the length of each string:
- strings.stream(): This converts the strings list into a stream of strings.
- .filter(str -> str.length() <= 5) : This uses the filter operation to retain only the strings for which the length is less than or equal to 5 characters.
- .collect(java.util.stream.Collectors.toList()): This collects the filtered strings into a new list.
- System.out.println("Strings with length less than or equal to 5 characters:");: This line prints a header for the filtered strings.
- filteredStrings.forEach(System.out::println);: This line iterates through the filteredStrings list and prints each filtered string.
Source Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GreaterFiveChar
{
public static void main(String[] args)
{
List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig");
System.out.println("Given String : " + strings);
// Using Lambda Expression to filter out strings with length greater than 5
List<String> filteredStrings = strings.stream()
.filter(str -> str.length() <= 5)
.collect(java.util.stream.Collectors.toList());
// Print the filtered strings
System.out.println("Strings with length less than or equal to 5 characters:");
filteredStrings.forEach(System.out::println);
}
}
Output
Given String : [apple, banana, cherry, date, elderberry, fig]
Strings with length less than or equal to 5 characters:
apple
date
fig