题解 | #成绩排序#二维数组排序
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.math.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.stream.*; import java.util.regex.*; import java.util.function.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int count = Integer.parseInt(in.nextLine()); boolean asc = "1".equals(in.nextLine()) ? true : false; // 二维数组排序 String[][] scores = new String[count][2]; for (int i = 0; i < count; i++) { String[] a = in.nextLine().split(" "); scores[i] = a; } Arrays.sort(scores, new Comparator<String[]>() { @Override public int compare(String[] s1, String[] s2) { if (asc) { return Integer.parseInt(s1[1]) - Integer.parseInt(s2[1]); } else { return Integer.parseInt(s2[1]) - Integer.parseInt(s1[1]); } } }); Arrays.stream(scores).forEach(s -> { System.out.printf("%s %s\n", s[0], s[1]); }); } // public static void main(String[] args) { // Scanner in = new Scanner(System.in); // int count = Integer.parseInt(in.nextLine()); // boolean asc = "1".equals(in.nextLine()) ? true : false; // 两次构建 map 使用 treemap // Map<String, Integer> map = new HashMap<>(); // while (in.hasNextLine()) { // String[] scores = in.nextLine().split(" "); // map.put(scores[0], Integer.parseInt(scores[1])); // } // // System.out.println(map); // TreeMap<String, Integer> treeMap = new TreeMap<>(new Comparator<String>() { // @Override // public int compare(String o1, String o2) { // if (asc) { // return map.getOrDefault(o1, 0) - map.getOrDefault(o2, 0); // } else { // return map.getOrDefault(o2, 0) - map.getOrDefault(o1, 0); // } // } // }); // treeMap.putAll(map); // treeMap.entrySet().forEach(s -> { // System.out.printf("%s %d\n", s.getKey(), s.getValue()); // }); // } }