DEV Community

realNameHidden
realNameHidden

Posted on

5 1 1 1 1

Java scenario based interview questions

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
    }
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →