You have a list of strings: ["apple", "banana", "cherry", "date", "fig", "grape"].
Write a code snippet to filter out strings starting with the letter 'b' and collect the remaining strings into a comma-separated single string.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape");
// Filter strings not starting with 'b' and join them into a single string
String result = fruits.stream()
.filter(fruit -> !fruit.startsWith("b")) // Exclude strings starting with 'b'
.collect(Collectors.joining(", ")); // Join remaining strings with ", "
System.out.println(result); // Output: apple, cherry, date, fig, grape
}
}
Explanation
filter(fruit -> !fruit.startsWith("b")): Filters out strings that start with the letter 'b'.
Collectors.joining(", "): Combines the remaining strings into a single string, separated by ", ".
System.out.println(result): Prints the final result.
Output
For the input ["apple", "banana", "cherry", "date", "fig", "grape"], the output will be:
apple, cherry, date, fig, grape
Top comments (0)