如何在多值hashmap中值搜索为true时打印键?

pdkcd3nj  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(217)

所以我最近创建的程序,hashmap中有多个值,下面是程序:

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);,但它不起作用,谁能帮我,告诉我我应该把什么程序,谢谢。

6jjcrrmo

6jjcrrmo1#

您可以使用以下代码:

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!");
    }

相关问题