adam bien's blog

Formatting String Lists with Collector#joining, Prefix and Suffix 📎

The method Collector#joining is overloaded with the parameters CharSequence prefix, CharSequence suffix which make List formatting easier:

import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;


public class CollectorsJoiningTest {

    @Test
    public void withPrefixAndSuffix() {
        var words = List.of("java","duke","jvm");
        var message = words.stream().collect(Collectors.joining(",", "[", "]"));
        System.out.println(message);
    }
}

The unit test prints: [java,duke,jvm]