Write a Java program using Lambda Expression to find the first non-empty string in a list of strings
The java program that finds the first non-empty string in a list of strings using Java Streams. Here's an explanation of the code:
- An ArrayList named fruits is created to store a list of strings. Some of the strings in the list are empty (i.e., ""), and some are non-empty.
- System.out.println("Given String : " + fruits); prints the original list of strings.
- The program uses Java Streams to filter and find the first non-empty string:
- fruits.stream(): This converts the fruits list into a stream of strings.
- .filter(s -> !s.isEmpty()): This is a filter operation that retains only the strings in the stream that are not empty. The condition !s.isEmpty() checks if a string is not empty.
- .findFirst(): This retrieves the first element in the stream that satisfies the filter condition.
- .orElse("No non-empty string found"): This specifies a default value to return if no non-empty string is found in the stream.
- System.out.println("First Non-Empty String : " + firstnonemptystring); prints the first non-empty string or the default message if no non-empty string is found.
Source Code
import java.util.ArrayList;
import java.util.List;
public class FirstNonEmptyString
{
public static void main(String[] args)
{
List<String> fruits = new ArrayList<>();
fruits.add("");
fruits.add("banana");
fruits.add("");
fruits.add("oranges");
fruits.add("date");
System.out.println("Given String : " + fruits);
String firstnonemptystring = fruits.stream().filter(s -> !s.isEmpty()).findFirst().orElse("No non-empty string found");
System.out.println("First Non-Empty String : " + firstnonemptystring);
}
}
Output
Given String : [, banana, , oranges, date]
First Non-Empty String : banana