Collections
framework to access prepackaged data structure.
- List
- Queue
- Stack
- Set
- Map
- Synchronized Collections
- Concurrent Collections
- Common Methods in Collections
- Default Sizes & Load Factors
- Utility Class - Collections
- Comparable vs Comparator
- Iterators
List
Ordered, index based, allow duplicates, Dynamic size.
- ArrayList: dynamic array, default size-10, new size = (current_size x 0.5)+1, null allowed, load factor 0.75.
- LinkedList: Doubly-linked list, elements connected using pointers.
- Vector: thread safe, same like arraylist, Deprecated
- CopyOnWriteArrayList: Modifications implemented in fresh copy
Queue
follows the First-In-First-Out (FIFO) principle.
Note: in java there is no impl for direct Queue
- LinkedList queue:
Queue<String> queue = new LinkedList<>();
- PriorityQueue: ordered in FIFO or by comparator. ie min heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
- ArrayDeque : doubled ended queue using array, used as both FIFO & LIFO.
Deque<String> deque = new ArrayDeque<>();
- SynchronousQueue
Queue methods: peek(), poll(), remove()
- peek(): return object at top of current queue
- poll(): return object and remove queue value, or return null if queue empty
- remove(): same as poll(), but throw NoSuchElementException if queue empty
Stack.
follows LIFO principle. elements added and removed in same end.
Stack<String> stack = new Stack<>();
- Stack: legacy class of stack but not recommended.
- ArrayDeque: double ended queue, recommended instead of stack class.
Stack methods:
- peek(): return object at top of current stack
- pop(): return object and remove stack value, or return null if stack empty
- remove(): same as pop(), but throw NoSuchElementException if stack empty
Set:
does not allow duplicate elements.
- Hashset: does not allow duplicates, unordered
- LinkedHasedSet: does not allow duplicates, maintain order.
- TreeSet : ordered ascending.
- EnumSet: set impl for enum values.
- NavigableSet: provide navigation methods
Map:
maps keys value pair
- HashTable: legacy impl of map, not allow Null key/value, slow, thread safe
- HashMap: Null key allowed, not thread safe.
- hashcode of null always zero 0
- Need to override hashcode(to generate key) and equals(if collision happened) method
- to avoid collision(multiple keys mapping to the same bucket), hashmap do 1.Seperate chaning, 2.linear probing
Note: In java 8, Hashmap use balanced tree instead of linkedList after threshold_value=8.
- SynchronizedMap: synchornized wrapper around Map, has Failfast iterator, performance issue not preferred.
- ConcurrentHashMap: lock each record segment level, has FailSafe Iterator. Fast, preferred
- TreeMap: implements red black tree, wherein all elements ordered as per compareTo() method
- NavigableMap: provide navigation methods.
- LinkedHashMap: ordered HashMap
Common method in map
- keySet() -
Set<String> keys = map.keySet();
- values() -
Collection<Integer> values = map.values();
- entrySet() -
Set<Map.Entry<String, Integer>> entries = map.entrySet();
- size()
Looping through Map
- Using Iterator with while - map.keyset.iterator
Iterator itr = map.keyset().iterator(); //for map
Iterator itr = list.iterator(); //for list
while(itr.hasNext()){ map.get(it.next());}
1a. List Iterator: traverse front and back,
ListIterator i = list.listIterator();while (i.hasPrevious()) {System.out.print(i.previous() + " "); }
- Using keyset() in for:
for (String State : map.keySet()){ }
- Using Map.entry<K,V>method in for.
for (Map.Entry<String,Float> entry : map.entrySet()) {
System.out.println("Item: " + entry.getKey() + ", Price: " + entry.getValue());
}
for (Float item : list) {
System.out.println("Item: " + item);
}
- Using map foreach
map.forEach((k,v)->{ sysout(k+v)})
Synchronized Collection.
Not suitable for high-concurrency because:
- Single Lock: One lock for all operations causes delays when many threads try to access the collection.
- Performance Overhead: Locking each method adds extra time and slows down performance.
- Fail-Fast Iterators: Iterators throw ConcurrentModificationException if the collection changes while iterating.
Synchronized collection Methods
- Collections.synchronizedCollection(Collection c)
- Collections.synchronizedList(List list)
- Collections.synchronizedMap(Map<K,V> m)
- Collections.synchronizedSet(Set s)
- Collections.synchronizedSortedMap(SortedMap<K,V> m)
- Collections.synchronizedSortedSet(SortedSet s)
- Collections.singletonMap(“name”,”rajesh”); //cannot change it
Concurrent Collections:
Alternative to traditional collections providing concurrency.
- ConcurrentHashMap.
- CopyOnWriteArrayList
- CopyOnWriteArraySet.
- ConcurrentLinkedQueue: Non-blocking FIFO queue.
- ConcurrentLinkedDeque: Non-blocking double-ended queue.
- LinkedBlockingQueue: Bounded blocking FIFO queue.
- LinkedBlockingDeque: Bounded blocking double-ended queue.
- ArrayBlockingQueue: Bounded blocking queue backed by an array.
- PriorityBlockingQueue: Blocking priority queue.
- DelayQueue: Delayed task scheduling queue.
- SynchronousQueue: Zero-capacity queue for handoff designs.
- ConcurrentSkipListMap: Concurrent sorted map.
- ConcurrentSkipListSet: Concurrent sorted set.
Common Methods in Collection:
Add element
add(element)
, addAll(collection)
- ArrayList, Vector, CopyOnWriteArrayList
add(element), addFirst(element), addLast(element)
- LinkedList
put(key, value)
- HashMap, ConcurrentHashMap
add(element)
- HashSet, TreeSet
add(element)
, offer(element)
- PriorityQueue
Remove element
remove(index), remove(element), removeAll(collection)
- ArrayList, Vector, CopyOnWriteArrayList
remove(index), remove(element), removeFirst(), removeLast()
- LinkedList
remove(key), remove(key, value)
- Hashmap, ConcurrentHashMap
remove(element)
- HashSet, TreeSet
remove(element), poll()
- PriorityQueue, ConcurrentLinkedQueue
Retrive element
get(index)
- ArrayList, LinkedList, Vector, CopyOnWriteArrayList
get(key)
- HashMap, ConcurrentHashMap
peek
- PriorityQueue, ConcurrentLinkedQueue
Find element
indexOf(element), lastIndexOf(element)
- ArrayList, LinkedList, Vector, CopyOnWriteArrayList
containsKey(key), getOrDefault(key, defaultValue
- HashMap, ConcurrentHashMap
contains(element)
: HashSet
Default Sizes & Load Factors:
Collections |
Default Size |
Load factor |
growa by |
ArrayList |
10 |
0.75 |
50% of current size |
HashMap |
16 |
0.75 |
Double its size |
Utility class - Collections
- Collections.max()
- Collections.min()
- Collections.sort()
- Collections.shuffle()
- Collections.synchronizedCollection() - convert to synchronized
- Collections.binarySearch()
- Collections.disjoint() - returns true if two specified collections have no elements in common
- Collections.copy()
- Collections.reverse()
- Collections.unmodifiableList() - make list as final
Comparable vs Comparator
Comparable |
Comparator |
Single property sorting |
can write multiple property sorting |
Need to modify class |
does not need to modify class |
provides compareTo() |
provides compare() method |
Collections.sort(List) |
Collections.sort(List,comparator) |
Comparable
class Student implements Comparable{
String name; int age;
@override
public int compareTo(Student st){
if(age==st.age) return 0;
else if(age>st.age) return 1;
else return -1;
}
}
List<Student> stList = new ArrayList<Student>();//...fil the list
Collection.sort(stList);
Comparator
Class Student{ String name; int age;}
List<Student> stList = new ArrayList<Student>();//...fil the list
Comparator<Student> comp = new Comparator<Student>(){
public int compare(Student s1, Student s2){
if(st1.age==st2.age) return 0;
else if(st1.age>st2.age) return 1;
else return -1;
}
}
Collection.sort(stList, comp);
Iterators
traverse elements of a collection
- FailFast Iterator :
directly on the collection and detect concurrent modifications during iteration
- it works by checking internal flag called modCount, updated each time a collection is modified
- it will throw ConcurrentModificationException if modcount changes
Ex: ArrayList, HashMap , HashSet, LinkedList
- FailSafe :
- operate on a clone or copy of the collection,
- allowing safe traversal, even if the collection is modified during iteration.
- suits when collection modification are expected
Ex: CopyOnWriteArrayList, ConcurrentHashMap