Java Data Structure Cheat Sheet - Hash Table

HashMap is the hash table implementation in Java. Check this post for time complexity.

The methods include:
  • V put(K key, V value)
  • boolean containsKey(Object key)
  • V get(Object key)
  • V remove(Object key)
  • Set<K> keySet()
  • etc

Example

import java.util.HashMap;

import java.util.Map;


public class HashMapExample {


  public static void main(String[] args) {

    Map<String, Integer> map = new HashMap<String, Integer>();


    map.put("a", 1);

    map.put("b", 2);

    map.put("c", 3);


    System.out.println(map.get("a")); // 1

    System.out.println(map.get("z")); // null

    if (map.containsKey("b")) {

      System.out.println(map.get("b")); // 2

    }


    for (String key : map.keySet()) {

      int val = map.get(key);

      System.out.println(val); // 1, 2, 3 (in undefined order)

    }

  }


}


Sort
  • To sort by key, you can convert the key set into List and Collections.sort(), or you may consider using TreeMap instread.
  • To sort by value (and still keep the key-value relation), you may convert the pairs into a list of objects then sort it by the value.

Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

PyCharm: Quick Start