Skip to content
Home » How to Create a String From a List: One Item per Line

How to Create a String From a List: One Item per Line

close up photo of ledger s list

Here’s how to create a String from a List in Java: one item per line:

import java.util.List;

import static java.util.stream.Collectors.joining;

public final class PrintingAList {

    public static void main(String[] args) {
        List<Player> players = createList();

        String message = players.stream()
                                .map(Player::toString)
                                .collect(joining(System.lineSeparator()));

        System.out.println(message);
    }

    private static List<Player> createList() {
        var messi = new Player("Lionel Messi", "PSG", "Argentina", 42);
        var cr7 = new Player("Cristiano Ronaldo", "Juventus", "Portugal", 50);
        var lukaku = new Player("Romelu Lukaku", "Chelsea", "Belgium", 41);

        return List.of(messi, cr7, lukaku);
    }

    private record Player(String name, String club, String coutry, int numberOfGoals) {
    }
}

If you have any questions, leave a comment or send me a message on my social media.