DEV Community

realNameHidden
realNameHidden

Posted on

3 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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay