======Java Primer====== =====Maps===== ====Hash Maps==== HashMap hmap = new HashMap(); * O(l) lookup and insertion. * Can have one null key and multiple null values ====TreeMaps==== * are 0(logn) lookup and insertion. * But, **keys are ordered**! * No null keys * keySet()and values() return in ascending order ====LinkedHashMap==== **An OrderedDict!** Same as hashMap but preserves **insertion order**. O(1) insertion and lookup. * Can have one null key and multiple null values * O(l) lookup and insertion. map.getOrDefault(key, default_value); ====HashSet==== HashSet h = new HashSet(); h.add"(a"); h.add("b"); Iterator i = h.iterator(); while (i.hasNext()) { System.out.println(i.next()); } contains(), add(), isEmpty(), size(), clone() ====Map Iteration===== for ( Map.Entry entry : dups.entrySet() ) { Integer key = entry.getKey(); Integer value = entry.getValue(); } Or, loop through keys: for (String key : map.keySet()) { // ... } Or, loop through values for (Object value : map.values()) { // ... } Remove Map element based on key value: map.keySet().removeIf(e->(e>2)); map.entrySet().removeIf(entry -> entry.getValue().equals("test")); =====ArrayList Iteration===== Iterator iter = dups.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } =====HashSet Iteration===== Iterator it = hset.iterator(); while(it.hasNext()){ System.out.println(it.next()); } or for (String temp : hset) { System.out.println(temp); } =====Stacks===== import java.util.* Stack stack = new Stack<>();; pop(), peek(), push(), empty(), search() =====Queue===== import java.util.LinkedList; import java.util.Queue; Queue q = new LinkedList<>(); =====PriorityQueue===== https://www.geeksforgeeks.org/priority-queue-class-in-java-2/ poll(), remove(), add() class The_Comparator implements Comparator { public int compare(String str1, String str2) { String first_Str; String second_Str; first_Str = str1; second_Str = str2; return second_Str.compareTo(first_Str); } } PriorityQueue queue = new PriorityQueue(new The_Comparator()); =====DFS===== ====Traversing==== TreeNode cur = root; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; while(cur != null || =====NOTES===== * Vector is the same as ArrayList, but Vector is synchronized. Removing from Vector or ArrayList in O(n). * LinkedList has O(1) remove, LinkedList is a double linked list. ArrayList is single. * LinkedList is better with add(), remove. * ArrayList better with get(), set(). * Char to digit: s.charAt(num2Idx) - '0' =====TRICKS===== ====Log and division==== * a / b = Math.exp(Math.log(a) - Math.log(b)) ====Random==== //Random number from 0 to 5 Random rand = new Random(); int r = rand.nextInt(6); or //Number between 0.0 and 1.0; Math.random();