Java 8 Stream API: How to join a list of Strings using another character

Solutions to join a list of strings using another character in Java 8 Stream API and a lambda expression

Solution 1: Simple Logic

import java.util.List;
import java.util.stream.Collectors;

public class StringJoiner {

    public static String join(List<String> list, String delimiter) {
        return list.stream()
                // Add the delimiter after each element except the last
                .collect(Collectors.joining(delimiter, "", ""));
    }

    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie");
        String result = join(names, "-");
        System.out.println(result); // Output: Alice-Bob-Charlie
    }
}

Solution 2: Logic with a conditional flow

A solution to join a list of strings using another character in Java 8 stream API and lambda expression with a condition that the String is not equal to “Alice”

import java.util.Arrays;
import java.util.List;

public class StringJoiningExample {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Alice", "David");
        String delimiter = ", "; // Use comma as the delimiter

        // Use Stream API to filter, filter again, and join strings
        String joinedNames = names.stream()
                                      .filter(name -> !name.equals("Alice")) // Exclude "Alice"
                                      .distinct() // Remove duplicates
                                      .collect(Collectors.joining(delimiter));

        System.out.println("Joined names: " + joinedNames); // Output: Bob, Charlie, David
    }
}

Solution 3: Logic to find a distinct and sorted result

A solution to join a list of strings using another character in Java 11 stream API and lambda expression with a condition that the String is not equal to “Alice”. find distinct and sort the results in ascending order

import java.util.Arrays;
import java.util.List;

public class StringJoiningExample {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Alice", "David");
        String delimiter = ", "; // Use comma as the delimiter

        // Use Stream API to filter, filter again, and join strings
        String joinedNames = names.stream()
                                      .filter(name -> !name.equals("Alice")) // Exclude "Alice"
                                      .distinct() // Remove duplicates
                                      .collect(Collectors.joining(delimiter));

        System.out.println("Joined names: " + joinedNames); // Output: Bob, Charlie, David
    }
}

Do you have a specific requirement other than these? Feel free to ask in the comments we would like to help further 🙂

Further Readings

Spread the word!
0Shares

Leave a comment

Your email address will not be published. Required fields are marked *