5/6/2025
3.11. Collection, Map
Collection
A collection is an object that represents a group of objects
A collections framework is an architecture for representing and manipulating collections
Many different types of collection: arrays, lists, vectors, sets, queues, tables, dictionaries, and
maps
All collection objects implement Collection interface, with the exception of maps
Collection interface provides behaviors needed to manage a group of objects
Collections are differentiated by:
how they store objects in memory
how objects are retrieved and ordered
whether they allow null values or duplicate entries
Collection interface defines fundamental operations that any collection must support
Comparable Interface
5/6/2025 1
It’s a generic type.
Any class that implements this interface needs to implement compareTo method. This method
takes 1 object as an argument, and compares it to the current instance (this).
To sort an array using Arrays.sort(Object[] a), all elements in array need to implement
Comparable
Types like String, primitive wrapper classes (Integer, Character,…) are sortable because they
implement Comparable interface
Comparator Interface
Similar to Comparable interface
The compare method takes 2 arguments. It compares 2 arguments to one another
Often use Comparator as a nested class
Can sort an array using an overloaded version public static <T> void sort(T[] a, Comparator<? super T> c) ,
which takes Comparator as the second parameter
Method should be overriden when sorting collection
compareTo() from Comparable interface
This method is used by:
Collections.sort(list)
TreeSet , TreeMap (natural ordering)
Arrays.sort(array)
package day3.collectionmap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Student implements Comparable<Student> {
String name;
int age;
5/6/2025 2
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age); // sort by age
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class SortCollectionExample {
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Alice", 22),
new Student("Bob", 20),
new Student("Clinda", 23)
);
List<Student> sorted = new ArrayList<>(students);
Collections.sort(sorted); // uses compareTo()
System.out.println(sorted);
}
}
Iterator
An object that allows traversal over records in a collection
When getting an instance of an iterator, can call next method to get the next element in the list
Can use the hasNext method to check if any elements remain to be processed
5/6/2025 3
When an iterator is first created, its cursor position is pointed at a position before the first
element
The first call to the next method retrieves the 1st element and moves the cursor position to be
between the 1st and 2nd elements
Subsequent calls to the next method moves the iterator’s position through the list until there are
no elements left, meaning hasNext = false
List
Ordered collection
Can be sequenced in memory (ArrayList), or maintain links to the next and previous values
(LinkedList)
Queue
Collection for holding elements prior to processing
Often implemented as FIFO, but can also be implemented as LIFO (stack)
Set
Collection which contains no duplicate elements, and isn’t naturally sequenced or ordered
A Set may contain a single null element
No way to retrieve an item from a set
3 implementations: HashSet, LinkedHashSet, TreeSet
HashSet
Use hashing mechanisms to store items
O(1) for basic operations (add, remove, contains, size)
LinkedHashSet
5/6/2025 4
Extends HashSet class
Maintains insertion order of elements
Using doubly linked list between entries
O(1) for add, contains, remove operations
TreeSet
A collection that is automatically sorted and remains sorted as elements are added or removed
Use data structure that’s a derivative of binary search tree
Left node and its children are elements that are less than the parent node
Right node and its children are elements that are greater than the parent node
Trees remain balance as elements are added
O(log(n)) for add, remove, and contains operations
Elements which implement Comparable can be elements of a TreeSet
If elements don’t implement Comparable → must pass a Comparator to the constructor
Demo HashSet, LinkedHashSet, TreeSet:
package day3.collectionmap;
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
hashSet.add("Zebra");
hashSet.add("Apple");
hashSet.add("Banana");
System.out.println(hashSet); // Order is unpredictable
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Zebra");
5/6/2025 5
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
System.out.println(linkedHashSet); // Insertion order
Set<String> treeSet = new TreeSet<>();
treeSet.add("Zebra");
treeSet.add("Apple");
treeSet.add("Banana");
System.out.println(treeSet); // Natural order
}
}
Map
Collection which stores key and value pairs
Keys are a set (→ unique), the values are a seperate collection, the key keeps a reference to a
single value
HashMap
Use hashing mechanisms to store items
LinkedHashMap
Key value entry collection whose keys are ordered by insertion order
5/6/2025 6
TreeMap
Sorted by its keys
Keys need to implement Comparable, or be initialized with Comparator
Demo HashMap, LinkedHashMap, TreeMap:
package day3.collectionmap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Zebra", 1);
hashMap.put("Apple", 2);
hashMap.put("Banana", 3);
System.out.println(hashMap); // Order is unpredictable
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("Zebra", 1);
linkedHashMap.put("Apple", 2);
linkedHashMap.put("Banana", 3);
System.out.println(linkedHashMap); // Insertion order
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Zebra", 1);
treeMap.put("Apple", 2);
treeMap.put("Banana", 3);
System.out.println(treeMap); // Natural order
}
}
3.13. Java Stream and Lambda Expressions
5/6/2025 7
Lambda Expressions
Syntax: (parameter1, parameter 2, ….) → expression; or (parameter1, parameter2, …) → {code block};
The expression should return a value, if the corresponding interface’s method returns a value
Only functional interface supports lambda expression (functional interface: interface that has
one and only one abstract method)
Can be used to replace anonymous class
Example of Lambda Expressions:
package day3.lambdaexpressions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* This class illustrates using lambda expressions to sort people by their last name
*/
public class LambdaExpressionExample {
record Person(String firstName, String lastName){ //by default, static nested class
@Override
public String toString() {
return firstName + " " + lastName;
}
}
//Solution 1: using anonymous class
public static void sortUsingAnonymousClass(List<Person> people) {
people.sort(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.lastName.compareTo(o2.lastName);
}
});
}
//Solution 2: using lambda expression:
public static void sortUsingLambdaExpression(List<Person> people) {
people.sort((o1, o2) -> o1.lastName.compareTo(o2.lastName));
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(Arrays.asList(
new LambdaExpressionExample.Person("Lucy", "Van Pelt"),
new Person("Sally", "Brown"),
new Person("Linus", "Van Pelt"),
new Person("Peppermint", "Patty"),
new Person("Charlie", "Brown")
5/6/2025 8
));
List<Person> people2 = people;
//Before sorting:
System.out.println(people);
System.out.println(people2);
//Implement sorting:
sortUsingAnonymousClass(people);
sortUsingLambdaExpression(people2);
//After sorting:
System.out.println(people);
System.out.println(people2);
}
}
5/6/2025 9