dev-resources.site
for different kinds of informations.
Java scenario based interview questions
Published at
12/15/2024
Categories
java
interview
scenario
collection
Author
realNameHidden
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
Articles
12 articles in total
verify() method in Mockito example
read article
List.of() vs Arrays.asList() in java
read article
@PreConstruct and @PostConstruct annotation Spring Boot Example
read article
With Spring can I make an optional path variable?
read article
Java Stream Scenario Based Interview Question
read article
Java scenario based interview questions
currently reading
How does Optional.ifPresent() differ from Optional.orElse()?
read article
How does the limit() method differ from the skip() method in streams?
read article
Java Streams | What is the difference between sorted() and distinct() in streams?
read article
How does reduce() differ from collect() in Java streams?
read article
Java’s TreeMap.tailMap() Method Explained
read article
Java Stream.distinct()
read article
Featured ones: