⚡0 XP🔥0

Collections and Generics

Lesson 13 of 15 ⏱ 7 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Java

The Collections Framework - List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap), Queue/Deque, iterating, sorting with Comparator, and generic classes and methods.

Arrays have a fixed size. Real programs need groups of objects that grow, shrink, avoid duplicates or look things up by key. The Java Collections Framework (java.util) provides ready-made data structures for all of these.

Collection
├── List   (ordered, duplicates allowed)   ArrayList, LinkedList
├── Set    (no duplicates)                 HashSet, LinkedHashSet, TreeSet
└── Queue  (processing order)              ArrayDeque, PriorityQueue, LinkedList

Map (key → value, unique keys)             HashMap, LinkedHashMap, TreeMap

Generics in one minute#

Collections use generics - the type in angle brackets says what they hold:

List<String> names = new ArrayList<>();   // only Strings allowed
names.add("Asha");
// names.add(42);                         // compile error - type safety!
String first = names.get(0);              // no cast needed

Generics work with objects only, so use wrapper types: List<Integer>, Map<String, Double>. Java converts between int and Integer automatically (autoboxing).

ArrayList - a resizable list#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
[Java, C++, Python, SQL] size 4
get(2): Python
[Java, C++, MySQL]
contains Java? true, index of MySQL: 2
sorted: [C++, Java, MySQL]
C++ JAVA MYSQL 
हिंदी में समझें

ArrayList एक ऐसा array है जो अपने आप बढ़ता-घटता है। add से जोड़ें, get(i) से पढ़ें, set से बदलें, remove से हटाएँ और size() से गिनती लें। <String> (generics) बताता है कि इसमें सिर्फ़ String ही रखी जा सकती हैं - गलत type डालने पर compiler ही रोक देता है।

Common Mistake

For a List<Integer>, list.remove(1) removes the element at index 1, not the value 1. To remove the value, write list.remove(Integer.valueOf(1)).

LinkedList and ArrayDeque#

LinkedList is fast at inserting/removing at the ends; ArrayDeque is the recommended stack/queue:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Back button: page3, now on page2
Serving Asha, next Ravi
PriorityQueue order: 10 30 40 70 

Sets - unique elements#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
unique count: 4
LinkedHashSet: [Indore, Bhopal, Ujjain, Dewas]
TreeSet: [Bhopal, Dewas, Indore, Ujjain]
add Indore again? false
union [1, 2, 3, 4, 5], intersection [3, 4]

Maps - key → value#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
pen: 100
stapler: null
stapler (default): 0
has notebook? true
eraser -> 100
notebook -> 45
pen -> 100
keys [eraser, notebook, pen], values [100, 45, 100]

Counting with a map - a pattern you will use forever#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
{be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=2}
{m=1, i=4, s=4, p=2}

Sorting objects with Comparator#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Aditi 9.47
Nisha 9.47
Kabir 9.16
Yash 7.78
By city: [Yash, Aditi, Nisha, Kabir]

Iterating safely and removing while iterating#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Passed: [72, 91, 66]
Without toppers: [72, 66]
Common Mistake

Removing from a list inside a for-each loop throws ConcurrentModificationException. Use an Iterator or removeIf.

Writing your own generic class and method#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
(Java, 1995) -> 4
17
zebra fruit

Which collection should I use?#

Need Use
ordered list with index access ArrayList
unique values, fast lookup HashSet
unique values in sorted order TreeSet
key → value, fast HashMap
key → value, sorted by key TreeMap
key → value, insertion order LinkedHashMap
stack or queue ArrayDeque
always take the smallest/highest priority PriorityQueue

Summary#

  • Use interfaces as variable types (List, Set, Map) and pick the implementation for the behaviour you need.
  • Generics (List<String>) give compile-time type safety; use wrapper types for primitives.
  • getOrDefault and merge make counting easy; Comparator.comparing(...).thenComparing(...) sorts objects.
  • Remove while iterating with an Iterator or removeIf.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Marks report with ArrayList

Read n marks into an ArrayList<Integer>, then print the list, the highest (use Collections.max) and the list sorted in descending order:

Marks: [67, 92, 45, 88, 73]
Highest: 92
Descending: [92, 88, 73, 67, 45]
Test input:
5
67 92 45 88 73
Expected output:
Marks: [67, 92, 45, 88, 73]
Highest: 92
Descending: [92, 88, 73, 67, 45]
2

City counts with TreeMap

Read city names until the input ends and print each city with its count, alphabetically, as Bhopal=2 lines.

Test input:
Indore Bhopal Indore Ujjain Dewas Indore Bhopal
Expected output:
Bhopal=2
Dewas=1
Indore=3
Ujjain=1

Quick Quiz

Q1.

Which collection keeps elements in insertion order and allows duplicates?

Q2.

Why can't you write ArrayList<int>?

Q3.

Which Map keeps keys sorted?

Q4.

What does map.getOrDefault("x", 0) return if "x" is missing?

Q5.

What is the main benefit of generics?