简体   繁体   中英

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

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));

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++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM