Write a Java program that sorts comma-separated strings in ascending order and joins them into one string.

Split the input on commas, trim each value, sort the values in ascending (alphabetical) order, and join them back into a single string.

Key Points

import java.util.Arrays;
import java.util.stream.Collectors;

public class SortCommaSeparated {

    public static void main(String[] args) {
        String input = "kafka, java, spring, docker, aws";

        String sorted = Arrays.stream(input.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .sorted()
                .collect(Collectors.joining(","));
        System.out.println(sorted);

        // Same values glued together without a separator
        System.out.println(sorted.replace(",", ""));
    }
}

Output

aws,docker,java,kafka,spring

awsdockerjavakafkaspring

Good to Know

To read the input from the user, wrap System.in in a Scanner and call nextLine(); the rest of the program stays the same.

Ask whether the sort should be case-sensitive and what separator the output needs; clarifying requirements is part of what is being assessed.

Interview Tip

A concise interview answer is

I split the input on commas, trim each value, drop empty ones, sort them in natural order and join them with Collectors.joining(). Sorting makes it O(n log n), and I would switch to String.CASE_INSENSITIVE_ORDER if case should not affect the order.

Last updated: 11 November 2026

Previous question: Two Sum: given an array of integers and a target, return the indices of the two numbers that add up to the target.

Next question: Check if all characters in a string have the same number of occurrences.

More Java Coding Questions interview questions

All Java Coding Questions questions