如何在多值HashMap中找到目标值时输出对应的Key?
如何在多值HashMap中根据目标值找到对应的Key?
嘿,我来帮你搞定这个问题!你的需求是根据输入的学生ID(比如P2530230),找到对应的导师ID(也就是HashMap里的Key)对吧?咱们先理清楚现有代码的问题,再一步步修改。
现有代码的问题
你当前用studentID.values().stream().anyMatch(...)只能判断目标值是否存在,但没办法记录下对应的Key——这就是为啥你没法输出导师ID的核心原因。另外你提到的studentID.contains.Values(SearchValue)是拼写错误,正确的方法是containsValue(),但这个方法是精确匹配整个Value字符串,而你的Value是把多个学生ID拼接在一起的(比如"P2530230P2534141"),所以精确匹配肯定找不到目标值,自然没效果。
修改方案:遍历EntrySet获取匹配的Key
我们需要同时访问HashMap的Key和Value,这时候用entrySet()就最合适了。通过Stream过滤出那些Value包含目标值的Entry,然后提取对应的Key即可。
修改后的完整代码如下:
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; public class MentorSearch { public static void main(String[] args) { Map<String, String> studentID = new HashMap<>(); studentID.put("P2530001", "P2530230" + "P2534141"); studentID.put("P2531120", "P2530201"); Scanner sc = new Scanner(System.in); System.out.print("Enter P number to search: "); String SearchValue = sc.nextLine(); // 过滤出所有Value包含目标值的Key List<String> matchingMentors = studentID.entrySet().stream() .filter(entry -> entry.getValue().contains(SearchValue)) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!matchingMentors.isEmpty()) { System.out.println("The P number that you entered is: " + SearchValue); System.out.println("P number exist, here is the assigned mentor:"); // 输出所有匹配的导师ID(如果有多个的话) matchingMentors.forEach(System.out::println); } else { System.out.println("The P number that you entered is: " + SearchValue); System.out.println("P number does not exist!"); } sc.close(); } }
代码细节解释
entrySet():获取HashMap中所有的键值对(Entry),这样我们能同时拿到Key(导师ID)和Value(学生ID拼接字符串)。filter(entry -> entry.getValue().contains(SearchValue)):过滤出Value中包含目标学生ID的Entry,解决了精确匹配的问题。map(Map.Entry::getKey):把符合条件的Entry转换成对应的Key(导师ID),提取我们需要的结果。collect(Collectors.toList()):把所有匹配的导师ID收集到List中,既可以判断是否存在,也能支持多个导师对应同一个学生的场景。
这样修改后,不仅能判断目标值是否存在,还能准确输出对应的导师ID啦~
内容的提问来源于stack exchange,提问作者Anthony1215
相关产品推荐
相关产品推荐

