题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < size; i++){ int index = sc.nextInt(); int value = sc.nextInt(); map.put(index, map.getOrDefault(index, 0)+value); } ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>(){ public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){ return o1.getKey()-o2.getKey(); } } ); for(Map.Entry<Integer, Integer> entry : list){ System.out.println(entry.getKey() + " " + entry.getValue()); } } }
关键在于对map的排序,有两个方法
1.使用TreeMap代替HashMap
2.将HashMap中的entrySet取出到List中,再进行排序