题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i = scanner.nextInt();//首次输入值,确定接下来键值对个数 HashMap<Integer, String> h = new HashMap<>(i);//新建确定存储个数的无序hashmap for (int j = 0; j <i; j++) { Integer key = (scanner.nextInt()); String value = String.valueOf(scanner.nextInt()); if (h.get(key)==null) {//如果hashmap中键对应值为空,则执行插入操作 h.put(key, value); }else {//如果hashmap中键对应值不为空,则取出旧的值相加新的值 String s1 = h.get(key); int i1 = Integer.parseInt(s1) + Integer.parseInt(value); String s2 = String.valueOf(i1); h.put(key,s2);//相加后重新放入 } } Set<Integer> integers = h.keySet();//返回hashmap中所有 key 组成的 Set 视图 ArrayList<Integer> integers1 = new ArrayList<>(integers); Collections.sort(integers1);//对set视图集合升序重新排序 LinkedHashMap<Integer,String> linkedHashMap = new LinkedHashMap<Integer, String>(i); /* 此处是排序操作 */ for (int y = 0; y < integers1.size(); y++) { linkedHashMap.put(integers1.get(y),h.get(integers1.get(y)));//根据升序排序后的list集合重新向有序的LinkedHashMap内存值 } /* 此处是遍历输出操作 */ Iterator<Map.Entry<Integer, String>> it = linkedHashMap.entrySet().iterator(); while (it.hasNext()){ Map.Entry<Integer, String> next = it.next(); System.out.println(next.getKey()+" "+next.getValue()); } } }