15

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

Clayton Louden
  • 1,056
  • 2
  • 11
  • 28
Rasshu
  • 1,764
  • 6
  • 22
  • 53

2 Answers2

31

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));
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • Actually, I had to type aprovados instead of list, so: for (String element : [ARRAY NAME HERE]) { System.out.println(element); } – Rasshu Oct 16 '12 at 13:29
1

If one wants to display each element in the same line, without those brackets:

public static void main(String[] args) {
    Set<String> stringSet = new LinkedHashSet<>();
    stringSet.add("1");
    stringSet.add("2");
    stringSet.add("3");
    stringSet.add("4");
    stringSet.add("5");
    int i = 0;
    for (String value : stringSet) {
        if (i < stringSet.size()-1) {
            System.out.print(value + ",");
        } else {
            System.out.print(value);
        }
        i++;
    }
}
Rasshu
  • 1,764
  • 6
  • 22
  • 53