Java 在多值hashmap中值搜索为true时如何打印键?
我最近创建的程序,hashmap中有多个值,下面是程序:Java 在多值hashmap中值搜索为true时如何打印键?,java,data-structures,Java,Data Structures,我最近创建的程序,hashmap中有多个值,下面是程序: studentID.put("P2530001", "P2530230" + "P2534141"); studentID.put("P2531120", "P2530201"); String SearchValue = sc.nextLine(); boolean found = studentID.va
studentID.put("P2530001", "P2530230" + "P2534141");
studentID.put("P2531120", "P2530201");
String SearchValue = sc.nextLine();
boolean found = studentID.values().stream().anyMatch(value -> value.contains(SearchValue));
if (found == true) {
System.out.println("The P number that you entered is: " + SearchValue);
System.out.println("P number exist, here is the assigned mentor:");
System.out.println();// print the key when passed value search
} else {
System.out.println("The P number that you entered is: " + SearchValue);
System.out.println("P number does not exist!");
}
我已尝试使用studentID.contains.Values(SearchValue);,但它不起作用,请任何人帮助并告诉我应该在程序中输入什么,谢谢。您可以使用以下代码:
Optional<Map.Entry<String, String>>
result = studentID.entrySet().stream().filter(e -> e.getValue().contains(SearchValue)).findFirst();
if (result.isPresent()) {
System.out.println("The P number that you entered is: " + SearchValue);
System.out.println("P number exist, here is the assigned mentor:");
System.out.println(result.get().getKey());// print the key when passed value search
} else {
System.out.println("The P number that you entered is: " + SearchValue);
System.out.println("P number does not exist!");
}
可选
结果=studentID.entrySet().stream().filter(e->e.getValue().contains(SearchValue)).findFirst();
if(result.isPresent()){
System.out.println(“您输入的P编号为:“+SearchValue”);
System.out.println(“存在P号,这里是指定的导师:”);
System.out.println(result.get().getKey());//在传递值搜索时打印键
}否则{
System.out.println(“您输入的P编号为:“+SearchValue”);
System.out.println(“P编号不存在!”);
}
问题:P数字在hashmap中既是键又是值。这是目的吗?你们的hashmap应该在这里表示什么?所以表示mentor的键,值是mentees,当搜索mentees值时,mentor(键)应该显示在屏幕上给用户看