Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 852
Rasshu Avatar asked Oct 15 '12 00:10

Rasshu


People also ask

How can you print each item of this array on a separate line?

To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.

How to print array elements in line by line JavaScript?

Use the join() method to combine the array into one string and separate each entry by by <br> to print array on separate lines in JavaScript.

How to print in separate line in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


1 Answers

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));
like image 123
FThompson Avatar answered Nov 15 '22 18:11

FThompson