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

Chương trình Java cập nhật value của HashMap bằng key


Trong bài viết này, chúng ta sẽ hiểu cách cập nhật value của HashMap bằng key. Java HashMap là triển khai bảng băm 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=1, Scala=2, Python=3}

Đầu ra mong muốn:

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

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, khởi tạo phần tử bằng 'put' 
Bước 5 - Hiển thị hashmap 
Bước 6 - Lấy value cụ thể bằng key với phương thức 'get' 
Bước 7 - Cộng thêm giá trị vào value vừa lấy 
Bước 8 - Hiển thị value đã cập nhật 
Bước 9 - DỪNG

Ví dụ 1

Gom tất cả thao tác dưới hàm 'main'.

import java.util.HashMap; 

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("Java", 1); 
        input_map.put("Scala", 2); 
        input_map.put("Python", 3); 
        System.out.println("The HashMap is defined as: " + input_map); 
        int value = input_map.get("Scala"); 
        value = value + 10; 
        input_map.put("Scala", value); 
        System.out.println("\nThe HashMap with the updated value is: " + input_map); 
    } 
}

Kết quả

The required packages have been imported 
The HashMap is defined as: {Java=1, Scala=2, Python=3} 
The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

Ví dụ 2

Đó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; 

class Demo { 
    static void update(HashMap input_map, String update_string){ 
        int value = input_map.get(update_string); 
        value = value + 10; 
        input_map.put("Scala", value); 
        System.out.println("\nThe HashMap with the updated value is: " + input_map); 
    } 
    
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        HashMap input_map = new HashMap<>(); 
        input_map.put("Java", 1); 
        input_map.put("Scala", 2); 
        input_map.put("Python", 3); 
        System.out.println("The HashMap is defined as: " + input_map); 
        String update_string = "Scala"; 
        update(input_map, update_string); 
    } 
}

Kết quả

The required packages have been imported 
The HashMap is defined as: {Java=1, Scala=2, Python=3} 
The HashMap with the updated value is: {Java=1, Scala=12, Python=3}