Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

HashMap

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

HashMap သည် data ကို key-value pair အဖြစ်သိမ်းတဲ့ collection ဖြစ်ပါတယ်။ Array/List မှာ index နဲ့ယူရပေမယ့် HashMap မှာ key နဲ့ယူပါတယ်။ ဥပမာ username နဲ့ user role, product code နဲ့ price, country နဲ့ capital city တို့ကိုသိမ်းရာမှာအဆင်ပြေပါတယ်။

java
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> productPrices = new HashMap<String, Integer>();

    productPrices.put("Keyboard", 50);
    productPrices.put("Mouse", 25);
    productPrices.put("Monitor", 200);

    System.out.println(productPrices);
    System.out.println("Mouse price: " + productPrices.get("Mouse"));
    System.out.println("Has Keyboard: " + productPrices.containsKey("Keyboard"));
  }
}

HashMap<String, Integer> သည် key ကို String, value ကို Integer အဖြစ်သိမ်းမယ့် map ပါ။ put() နဲ့ data ထည့်ပြီး get(key) နဲ့ value ယူပါတယ်။ containsKey() က key ရှိ/မရှိစစ်ပါတယ်။

You should see
{Mouse=25, Keyboard=50, Monitor=200} Mouse price: 25 Has Keyboard: true

လက်တွေ့အသုံးချမှု

User settings, product prices, API response mappings, translation dictionaries, cache data တွေမှာ HashMap အသုံးများပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Key spelling/case မှားရင် value မတွေ့ပါ။ Mouse နဲ့ mouse မတူပါဘူး။