User Tools

Site Tools


java_primer

This is an old revision of the document!


Java Primer

Maps

Hash Maps

HashMap<Integer, String> 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

LinkedHashMap

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<String> h = new HashSet<String>(); 

h.add"(a");
h.add("b");
Iterator<String> i = h.iterator(); 
while (i.hasNext()) {
   System.out.println(i.next()); 
}

contains(), add(), isEmpty(), size(), clone()

Map Iteration

for ( Map.Entry<Integer, Integer> 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<Integer> iter = dups.iterator();
    while (iter.hasNext()) {
       System.out.println(iter.next());
    }

HashSet Iteration

     Iterator<String> 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<Integer> stack = new Stack<>();;

pop(), peek(), push(), empty(), search()

Queue

import java.util.LinkedList; 
import java.util.Queue;
Queue<Integer> q = new LinkedList<>();

PriorityQueue

https://www.geeksforgeeks.org/priority-queue-class-in-java-2/

poll(), remove(), add()

class The_Comparator implements Comparator<String> { 
    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<String> queue = new 
PriorityQueue<String>(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().
java_primer.1597936924.txt.gz · Last modified: 2020/08/20 15:22 by jrseti