Skip to main content

Command Palette

Search for a command to run...

set map

Published
1 min readView as Markdown
import java.util.*;

public class HashMapHashSetBasics {
    public static void main(String[] args) {

        System.out.println("🔹 HashMap Example:");

        HashMap<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 2);
        map.put("orange", 5);
        map.put("banana", 4);  // Overwrites value for "banana"

        System.out.println("Value for 'apple': " + map.get("apple")); // 3
        map.remove("orange");
        System.out.println("Value for 'orange': " + map.get("orange")); // null

        // ⭐ getOrDefault example
        System.out.println("Value for 'mango' using get: " + map.get("mango")); // null
        System.out.println("Value for 'mango' using getOrDefault: " + map.getOrDefault("mango", 0)); // 0 (default)

        System.out.println("\n🔹 HashSet Example:");

        Set<String> set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("banana");  // Duplicate, will not be added

        System.out.println("Contains 'apple'? " + set.contains("apple")); // true
        set.remove("orange");
        System.out.println("Contains 'orange'? " + set.contains("orange")); // false
    }
}

More from this blog

Amit singh's blog

235 posts