Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

java - Display each list element in a separate line (console)

In this part of code:

    System.out.println("Alunos aprovados:");
    String[] aprovados = {"d", "a", "c", "b"};
    List<String> list = new ArrayList();
    for (int i = 0; i < aprovados.length; i++) {
        if (aprovados[i] != null) {
            list.add(aprovados[i]);
        }
    }

    aprovados = list.toArray(new String[list.size()]);
    Arrays.sort(aprovados);
    System.out.println(Arrays.asList(aprovados));

An example result of System.out.println is:

[a, b, c, d]

How could I modify the code above if I want a result like below?

a

b

c

d

Or, at least:

a,

b,

c,

d

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iterate through the elements, printing each one individually.

for (String element : list) {
    System.out.println(element);
}

Alternatively, Java 8 syntax offers a nice shorthand to do the same thing with a method reference

list.forEach(System.out::println);

or a lambda

list.forEach(t -> System.out.println(t));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...