Challenge: Sort by Length
Completed
Read n words. Sort them by length (shortest first); words of the same length stay in alphabetical order. Write the comparator as a nested static class that implements Comparator<String>. Print the words on one line separated by spaces.
Input
First n, then n words.
Output
The sorted words on one line.
Example
Input
5 banana fig apple kiwi date
Output
fig date kiwi apple banana
Editor
Java
Hints
static class ByLength implements Comparator<String> { public int compare(String a, String b) {...} }
String.join(" ", list) joins a list with spaces.
Solution explanation
A named comparator class can be reused anywhere you need this sort order.
Show solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
static class ByLength implements Comparator<String> {
public int compare(String a, String b) {
if (a.length() != b.length()) {
return a.length() - b.length();
}
return a.compareTo(b);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> words = new ArrayList<>();
for (int i = 0; i < n; i++) words.add(sc.next());
words.sort(new ByLength());
System.out.println(String.join(" ", words));
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module