there is a way to print elements of a String array sorted for word length at every line? So, considering the code below,
String[] arr = {"a", "b", "cc", "dd", "ee", "fff", "hhh"};
for (int i = 0; i < 5; i++) {
System.out.println(arr[i]);
}
there is a way to change the output from:
"ab cc dd ee fff hhh"
to
"ab
cc dd ee
fff hhh"
Thanks for any help.
I would use stream
for that job:
Arrays.stream(arr).collect(
Collectors.groupingBy(String::length,
Collectors.joining(" ")))
.values().forEach(System.out::println);
Output:
a b
cc dd ee
fff hhh
Before spoilering the answer, I will give you some hints:
Please try to code this yourself, as this helps you to better understand Java.
So here is my take on this problem. It doesn't involve using indices and avoids streams as this is not something a beginner should start with.
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();
}
}
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.