[英]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: System.out.println的示例结果是:
[a, b, c, d] [A B C D]
How could I modify the code above if I want a result like below? 如果我想要下面的结果,该如何修改上面的代码?
a 一种
b b
c C
d d
Or, at least: 或至少:
a, 一种,
b, b,
c, C,
d 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 另外,Java 8语法提供了一个很好的捷径,可以通过方法引用来完成相同的操作
list.forEach(System.out::println);
or a lambda 或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++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.