Java Collections Cheat Sheet — Essential Guide for Everyday Coding


💡 Introduction

The Java Collections Framework is a set of classes and interfaces for working with groups of objects. This cheat sheet gives you quick access to the most commonly used collections, methods, and examples.


💡 Key Interfaces

Collection<E>      // Root interface
List<E>            // Ordered, allows duplicates
Set<E>             // No duplicates
Queue<E>           // FIFO structure
Map<K, V>          // Key-value pairs

💡 Common Implementations

List     -> ArrayList, LinkedList
Set      -> HashSet, LinkedHashSet, TreeSet
Queue    -> LinkedList, PriorityQueue
Map      -> HashMap, LinkedHashMap, TreeMap, Hashtable

💡 List Examples

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.get(0);           // Apple
list.remove("Banana");

💡 Set Examples

Set<String> set = new HashSet<>();
set.add("Java");
set.add("Java");       // Duplicate, will be ignored
set.contains("Java");  // true

💡 Map Examples

Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.get(1);             // One
map.remove(2);

💡 Queue Examples

Queue<String> queue = new LinkedList<>();
queue.add("First");
queue.add("Second");
queue.poll();          // Removes and returns "First"
queue.peek();          // Returns "Second"

💡 Sorting Collections

Collections.sort(list);                            // Ascending order
Collections.sort(list, Collections.reverseOrder());

💡 Useful Methods

list.size();
set.isEmpty();
map.keySet();
map.values();
map.entrySet();

💡 Iteration Examples

for (String item : list) {
    System.out.println(item);
}

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

💡 Tips

  • Prefer ArrayList for fast access, LinkedList for frequent inserts/deletes.
  • Use HashSet for uniqueness and speed, TreeSet for sorted data.
  • HashMap is best for general-purpose key-value storage.

💡 Conclusion

Mastering Java Collections makes daily development smoother and more efficient. Bookmark this cheat sheet and boost your productivity!

More coming soon at ZeroToJavaPro.com!