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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay