Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java lấy key từ HashMap bằng value


Trong bài viết này, chúng ta sẽ hiểu cách lấy key từ HashMap bằng value. Java HashMap là triển khai bảng băm (hash table) của interface Map trong Java. Nó là tập hợp các cặp key-value.

Minh họa dưới đây:

Giả sử đầu vào là:

Input HashMap: {Java=8, Scala=5, Python=15} Key: 8

Đầu ra mong muốn:

The value of Key: 8 is Java

Thuật toán

Bước 1 - BẮT ĐẦU 
Bước 2 - Khai báo biến 
Bước 3 - Định nghĩa giá trị 
Bước 4 - Tạo HashMap kiểu Integer và String, khởi tạo phần tử bằng 'put' 
Bước 5 - Định nghĩa giá trị key 
Bước 6 - Duyệt qua các phần tử HashMap, kiểm tra key đã định nghĩa có trong HashMap 
Bước 7 - Nếu tìm thấy, thoát khỏi vòng lặp 
Bước 8 - Hiển thị kết quả 
Bước 9 - DỪNG

Ví dụ 1

Ở đây, gom tất cả thao tác dưới hàm 'main'.

import java.util.HashMap; 
import java.util.Map.Entry; 

public class Demo { 
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        HashMap input_map = new HashMap<>(); 
        input_map.put("Scala", 5); 
        input_map.put("Java", 8); 
        input_map.put("Python", 15); 
        System.out.println("The HashMap is defined as: " + input_map); 
        Integer Key = 8; 
        for(Entry entry: input_map.entrySet()) { 
            if(entry.getValue() == Key) { 
                System.out.println("\nThe value of Key: " + Key + " is " + entry.getKey()); 
                break; 
            } 
        } 
    } 
}

Kết quả

The required packages have been imported 
The HashMap is defined as: {Java=8, Scala=5, Python=15} 
The value of Key: 8 is Java

Ví dụ 2

Ở đây, đóng gói thao tác vào hàm thể hiện lập trình hướng đối tượng.

import java.util.HashMap; 
import java.util.Map.Entry; 

public class Demo { 
    static void get_value(HashMap input_map, Integer Key){ 
        for(Entry entry: input_map.entrySet()) { 
            if(entry.getValue() == Key) { 
                System.out.println("\nThe value of Key: " + Key + " is " + entry.getKey()); 
                break; 
            } 
        } 
    } 
    
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        HashMap input_map = new HashMap<>(); 
        input_map.put("Scala", 5); 
        input_map.put("Java", 8); 
        input_map.put("Python", 15); 
        System.out.println("The HashMap is defined as: " + input_map); 
        Integer Key = 8; 
        get_value(input_map, Key); 
    } 
}

Kết quả

The required packages have been imported 
The HashMap is defined as: {Java=8, Scala=5, Python=15} 
The value of Key: 8 is Java