Display each list element in a separate line (console)

后端 未结 2 1184
长情又很酷
长情又很酷 2020-12-16 17:30

In this part of code:

    System.out.println(\"Alunos aprovados:\");
    String[] aprovados = {\"d\", \"a\", \"c\", \"b\"};
    List list = new         


        
相关标签:
2条回答
  • 2020-12-16 18:01

    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));
    
    0 讨论(0)
  • 2020-12-16 18:16

    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++;
        }
    }
    
    0 讨论(0)
提交回复
热议问题