[英]Grouping array elements of same value in each line while printing - Java
有没有办法打印在每一行按字长排序的字符串数组的元素? 所以,考虑下面的代码,
String[] arr = {"a", "b", "cc", "dd", "ee", "fff", "hhh"};
for (int i = 0; i < 5; i++) {
System.out.println(arr[i]);
}
有一种方法可以改变输出:
“ab cc dd ee fff hhh”
到
"ab
cc dd ee
ffhhhh”
谢谢你的帮助。
我会使用stream
来完成这项工作:
Arrays.stream(arr).collect(
Collectors.groupingBy(String::length,
Collectors.joining(" ")))
.values().forEach(System.out::println);
输出:
a b
cc dd ee
fff hhh
在剧透回答之前,先给大家一些提示:
请尝试自己编写代码,因为这有助于您更好地理解 Java。
所以这是我对这个问题的看法。 它不涉及使用索引并避免使用流,因为这不是初学者应该开始的。
public static void main(String[] args) {
String[] arr = {"a", "b", "cc", "dd", "ee", "fff", "hhh"};
int previousLength = Integer.MAX_VALUE;
for (String currentString: arr){
if(previousLength < currentString.length()){
System.out.println("");
}
System.out.print(currentString+" ");
previousLength = currentString.length();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.