Skip to content

Instantly share code, notes, and snippets.

@dtinth
Created September 23, 2012 14:56
Show Gist options
  • Save dtinth/3771854 to your computer and use it in GitHub Desktop.
Save dtinth/3771854 to your computer and use it in GitHub Desktop.
Java vs Ruby
Sort the strings by length in ascending order.
If the string has same length, sort alphabetically, ignoring case.
Input:
- first line - "n", number of strings to sort
- n following lines - the string to sort
Output:
- n lines. each line is a string, in sorted order
puts Array.new(gets.to_i) { gets.strip }.sort_by { |string| [string.length, string.downcase] }
import java.util.*;
public class SortByLength {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] strings = new String[Integer.parseInt(scanner.nextLine())];
for (int i = 0; i < strings.length; i ++) {
strings[i] = scanner.nextLine();
}
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() == b.length() ? a.compareToIgnoreCase(b) : a.length() - b.length();
}
});
for (String string : strings) {
System.out.println("-" + string);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment