Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อรับคีย์จาก HashMap โดยใช้ค่า


ในบทความนี้ เราจะมาทำความเข้าใจวิธีรับคีย์จาก HashMap โดยใช้ค่า Java HashMapis ตารางแฮชตามการใช้งานอินเทอร์เฟซแผนที่ของ Java เป็นชุดของคู่คีย์-ค่า

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

สมมติว่าข้อมูลที่เราป้อนคือ

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

ผลลัพธ์ที่ต้องการจะเป็น

The value of Key: 8 is Java

อัลกอริทึม

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create a HashMap of integer and string values and initialize elements in it using the ‘put’ method.
Step 5 - Define a key value.
Step 6 - Iterate over the elements of HashMap, and check if the key previously defined is present in the HashMap.
Step 7 - If found, break away from the loop.
Step 8 - Display the result
Step 9 - Stop

ตัวอย่างที่ 1

ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'

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<String, Integer> 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<String, Integer> entry: input_map.entrySet()) {
         if(entry.getValue() == Key) {
            System.out.println("\nThe value of Key: " + Key + " is " + entry.getKey());
            break;
         }
      }
   }
}

ผลลัพธ์

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

The value of Key: 8 is Java

ตัวอย่างที่ 2

ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ

import java.util.HashMap;
import java.util.Map.Entry;
public class Demo {
   static void get_value(HashMap<String, Integer> input_map,Integer Key){
      for(Entry<String, Integer> 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<String, Integer> 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);
   }
}

ผลลัพธ์

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

The value of Key: 8 is Java