You need to enable JavaScript to run this app. Java实现HashMap按值排序时用户输入值未插入的问题如何修复
优惠活动
大模型
产品
解决方案
定价
更多

Java实现HashMap按值排序时用户输入值未插入的问题如何修复

问题根源
  • addUser()方法内部新建了独立的局部HashMap对象,你输入的用户数据都存在这个局部对象里,方法执行结束后该对象就被回收,完全没有修改到getUnSortedMap()中预存了默认值的原HashMap,因此数据无法生效。
  • Scanner输入处理存在逻辑bug:调用nextInt()读取用户输入的选择项后,输入缓冲区会残留换行符,后续调用nextLine()会直接读取到空值,且addUser()中重复调用了两次nextLine(),会导致输入的姓名被吞掉。
修复步骤
  1. 修改addUser()方法的定义,新增HashMap入参,直接在传入的原map上新增数据,不要在方法内新建HashMap
  2. 修正Scanner换行符处理逻辑,每次调用nextInt()后主动消费残留的换行符,避免后续读取空内容
  3. 在getUnSortedMap()中调用addUser()时,把当前预存了默认值的unsortMap作为参数传入
修复后完整代码
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class CFG {
    public static void main(String[] args) {
        sortByValueJava8Stream();
    }

    private static void sortByValueJava8Stream() {
        Map<String, Integer> unSortedMap = getUnSortedMap();
        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
        unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        System.out.println("Sorted Map   : " + sortedMap);
    }

    public static Map<String, Integer> getUnSortedMap() {
        Scanner in = new Scanner(System.in);
        HashMap<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("Shiran", 342);
        unsortMap.put("Hashini", 448);
        unsortMap.put("Chanchala", 398);
        unsortMap.put("Priyankara", 399);
        unsortMap.put("Mayuri", 350);
        unsortMap.put("Sameera", 321);
        unsortMap.put("Supun", 299);
        unsortMap.put("Supuni", 378);
        unsortMap.put("Kavindu", 384);
        unsortMap.put("Nadeeka", 440);

        System.out.println("Do you want to add more players? ");
        System.out.println("if yes pres 1 : ");
        Integer c = in.nextInt();
        // 吃掉nextInt残留的换行符
        in.nextLine();
        if (c == 1) {
            // 把原map传入addUser方法
            addUser(unsortMap);
        }
        return unsortMap;
    }

    // 方法接收原map作为参数
    public static void addUser(Map<String, Integer> unsortMap){
        Scanner in = new Scanner(System.in);
        // 去掉方法内新建HashMap的逻辑
        System.out.println("Enter name : ");
        String a = in.nextLine();
        // 去掉多余的nextLine调用
        System.out.println("Enter Time : ");
        Integer b = in.nextInt();
        unsortMap.put(a,b);
    }
}

修复后运行程序,你输入的用户数据会直接写入原HashMap,排序结果也会包含新增的条目。

内容的提问来源于stack exchange,提问作者Kasun Wimaladarma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 11:24:02