题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.Scanner; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case int count = in.nextInt(); int flag = in.nextInt(); in.nextLine(); List<String> list = new ArrayList<>(); Map<Integer, List<String>> map = new LinkedHashMap<>(); for (int i = 0; i < count; i++) { String line = in.nextLine(); if (line.isEmpty()) { continue; } String[] strs = line.split(" "); if (strs.length != 2) { continue; } if (map.containsKey(Integer.parseInt(strs[1]))) { List<String> value = map.get(Integer.parseInt(strs[1])); value.add(strs[0]); map.put(Integer.parseInt(strs[1]), value); } else { List<String> value = new ArrayList<>(); value.add(strs[0]); map.put(Integer.parseInt(strs[1]), value); } } Map<Integer, List<String>> result = new LinkedHashMap<>(); if (flag == 0) { // 降序 result = sortByDesc(map); } if (flag == 1) { // 升序 result = sortByAsc(map); } for (Map.Entry<Integer, List<String>> entry : result.entrySet()) { List<String> names = entry.getValue(); names.forEach(name -> System.out.println(name + " " + entry.getKey())); } } } private static Map<Integer, List<String>> sortByDesc(Map<Integer, List<String>> map) { Map<Integer, List<String>> result = new LinkedHashMap<>(); map.entrySet().stream().sorted(Collections.reverseOrder( Map.Entry.comparingByKey())).forEachOrdered(x -> result.put(x.getKey(), x.getValue())); return result; } private static Map<Integer, List<String>> sortByAsc(Map<Integer, List<String>> map) { Map<Integer, List<String>> result = new LinkedHashMap<>(); map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered( x -> result.put(x.getKey(), x.getValue())); return result; } }