0% found this document useful (0 votes)
53 views2 pages

Java Collections CheatSheet

Uploaded by

Aman kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views2 pages

Java Collections CheatSheet

Uploaded by

Aman kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Java Collections Cheat Sheet

ArrayList
• Syntax: ArrayList list = new ArrayList<>();
• Insertion: list.add(element); list.add(index, element);
• Access: list.get(index);
• Update: list.set(index, element);
• Deletion: list.remove(index); list.remove(Object);
• Size: list.size();
• Looping: for(Type x : list) { } or list.forEach(...);
• Sort: Collections.sort(list);

Stack
• Syntax: Stack stack = new Stack<>();
• Push: stack.push(element);
• Pop: stack.pop();
• Peek: stack.peek();
• Check empty: stack.isEmpty();
• Size: stack.size();

Queue
• Syntax: Queue queue = new LinkedList<>();
• Enqueue: queue.add(element); queue.offer(element);
• Dequeue: queue.remove(); queue.poll();
• Peek: queue.element(); queue.peek();
• Size: queue.size();

PriorityQueue (Min Heap & Max Heap)


• Min Heap Syntax: PriorityQueue pq = new PriorityQueue<>();
• Max Heap Syntax: PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder());
• Insertion: pq.add(element);
• Peek: pq.peek();
• Deletion: pq.poll();
• Size: pq.size();

HashMap (unordered)
• Syntax: HashMap map = new HashMap<>();
• Insert: map.put(key, value);
• Access: map.get(key);
• Delete: map.remove(key);
• Size: map.size();
• Check Key: map.containsKey(key);
• Looping: for(Map.Entry e : map.entrySet()) { }
LinkedHashMap (ordered)
• Syntax: LinkedHashMap map = new LinkedHashMap<>();
• Maintains insertion order.
• Methods same as HashMap.

HashSet (unordered)
• Syntax: HashSet set = new HashSet<>();
• Insert: set.add(element);
• Delete: set.remove(element);
• Check: set.contains(element);
• Size: set.size();
• Looping: for(Type x : set) { }

LinkedHashSet (ordered)
• Syntax: LinkedHashSet set = new LinkedHashSet<>();
• Maintains insertion order.
• Methods same as HashSet.

LinkedList (Singly & Doubly)


• Syntax: LinkedList list = new LinkedList<>();
• Insertion: list.add(element); list.addFirst(element); list.addLast(element);
• Deletion: list.remove(); list.removeFirst(); list.removeLast();
• Access: list.get(index);
• Size: list.size();
• Doubly LinkedList is supported internally by LinkedList class.

Pair
• Syntax: AbstractMap.SimpleEntry pair = new AbstractMap.SimpleEntry<>(key, value);
• Access: pair.getKey(); pair.getValue();
• Assign: pair.setValue(newValue);

You might also like