Collections. Practical Tasks
Add two boxes of the same weight to a TreeSet and only one of them stays in the set. If compareTo() compares nothing but the weight field, the second box counts as a duplicate and is silently dropped — no exception, no warning:
Set<HeavyBox> boxes = new TreeSet<>(); // compareTo() compares only weight
boxes.add(new HeavyBox(10, 20, 30, 5));
boxes.add(new HeavyBox(40, 50, 60, 5));
System.out.println(boxes.size()); // Output: 1 This page has 10 Java collections exercises — practice problems on List, Set, Queue and Map with ArrayList, TreeSet, HashSet, ArrayDeque, Iterator, HashMap and Comparable. The tasks follow the lessons of the Collections module: from lists to sets, queues and maps, and the last task continues the Online Store project from the earlier modules. Some tasks come with sample input and hints on version-specific APIs.
Which Collection Each Exercise Needs
Each exercise practices one collection and two or three of its key methods. If a method in the table is new to you, review the lesson in the right column first — then a task takes 20–40 minutes instead of an evening with the Javadoc.
| Exercise | Collection and methods | What to review |
|---|---|---|
| ArrayList of HeavyBox Objects | ArrayList: add(), get(), remove(), toArray(), clear() | List Interface and ArrayList |
| TreeSet Sorted by Weight | TreeSet, Comparable.compareTo() | SortedSet, NavigableSet and TreeSet, Comparable and Comparator |
| Remove Duplicate Numbers | HashSet / LinkedHashSet, String.split() | Set, HashSet and LinkedHashSet |
| union() and intersect() | addAll(), retainAll(), generic methods | Collection Interface |
| ArrayDeque Queue | ArrayDeque: offer(), poll() | Queue and Deque, ArrayDeque |
| Split a Collection | Iterator: hasNext(), next(), remove() | Iterator and ListIterator |
| HashMap of Books | HashMap: entrySet(), keySet(), values() | Map Interface, HashMap Internals |
| Students | Set, equals() / hashCode(), removal with an Iterator | Set and HashSet, Iterator |
| Map of Pets | Map<String, Pet>, polymorphism | Map Interface |
| Online Store | List, Comparator, List.sort() / Collections.sort() | Collections Class Methods |
ArrayList of HeavyBox Objects
- Create a dynamic array (
ArrayList) ofHeavyBoxobjects. - The class HeavyBox extends the class Box and has a field int weight.
- The class Box has the fields double width, double height, double depth.
- Print the contents of the list with a
for-eachloop. - Change the weight of the first box to 1.
- Remove the last box.
- Get an array of the boxes from the list in three different ways and print it to the console.
- Remove all boxes.
Hint
A collection gives you an array through toArray() (returns Object[]), toArray(new HeavyBox[0]) and, since Java 11, toArray(HeavyBox[]::new). Only the last two return a typed HeavyBox[]. To print an array, use Arrays.toString().
TreeSet of Boxes Sorted by Weight
- Create a TreeSet of
HeavyBoxobjects. - The class HeavyBox extends the class Box and has a field int weight.
- The class Box has the fields double width, double height, double depth.
HeavyBoxmust implement theComparableinterface; the boxes are sorted by the field weight.- Print the contents of the set with a
for-eachloop.
Remove Duplicate Numbers from a String with a Set
- The user enters a set of numbers as a single line: "1, 2, 3, 4, 4, 5, 10, 11".
- Remove the duplicate numbers from the line.
- Print the result to the console.
- Use the Set interface.
A detail
HashSet does not keep the input order. To print the numbers in their original sequence — 1, 2, 3, 4, 5, 10, 11 — use a LinkedHashSet. Split the line with split("\\s*,\\s*"): the spaces around the commas then do not end up inside the elements, and "4" and " 4" do not become two different strings.
Set Union and Intersection: union() and intersect()
- Write the methods
static <T> Set<T> union(Set<T> set1, Set<T> set2)andstatic <T> Set<T> intersect(Set<T> set1, Set<T> set2)that return the union and the intersection of two sets. - The methods must return a new set and must not modify
set1andset2. - Test both methods on sets filled with sample data.
ArrayDeque Queue: offer() and poll()
- Create a queue of
HeavyBoxobjects. - The class HeavyBox extends the class Box and has a field int weight.
- The class Box has the fields double width, double height, double depth.
- Use the class
ArrayDeque. - Add the boxes to the queue with the method
offer(). - Remove them with the method
poll().
Split a Collection with an Iterator
- Create a collection of
Boxobjects.public class Box { private double width; private double height; private double depth; public Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } public double getWidth() { return width; } // getHeight(), getDepth() and toString() work the same way } - Write a method that goes through the collection and checks the width of each box.
- If a box is wider than 30 cm, move it to another collection.
- Use an iterator to go through the elements.
HashMap of Books: entrySet(), keySet() and values()
- Create a HashMap that maps a book title to a book object (class Book).
- The class Book has the fields name, cost and author.
- Iterate over the key-value pairs and print them —
entrySet(). - Iterate over the book titles and print them —
keySet(). - Iterate over the books and print them —
values(). - Write a separate method for each kind of iteration.
One more way
After the three required versions, try a fourth one — books.forEach((name, book) -> System.out.println(name + ": " + book)) (Java 8). It is shorter, but inside it does the same as iterating over entrySet().
Students: Filter by Average Grade and Promote to the Next Year
- Create a class Student with a name, a group, a year of study and grades in several subjects (on a 5-point scale).
- Create a
Set<Student>of Student objects. Overrideequals()andhashCode()in Student. - Write a method that removes the students whose average grade is < 3.
- Write a method that promotes a student to the next year if the average grade is >= 3.
- Write a method
printStudents(Set<Student> students, int year)that takes a set of students and a year of study and prints the names of the students in that year.
Map of Pets: Name to Pet Object
- Create a class
Petwith a field name and an abstract method makeNoise(). - Create subclasses of
Pet—Cat,DogandParrot. Each class implements its own version of makeNoise(). - Create a map of pets where the key is the name of the pet and the value is a
Petobject. - Add different pets to the map.
- Write a method that prints all keys of the map.
- Write a method that calls makeNoise() for every pet.
Collections Instead of Arrays, Sorted Catalog
Online Store · part 6 of 6 · ← part 5
- Replace the arrays in your Online Store with collections.
- Keep the products of the catalog sorted, for example by price. Sort them with a
ComparatorandList.sort()orCollections.sort().
Where Collection Code Goes Wrong
Most mistakes in collections exercises do not break compilation: the code runs, but it loses elements, keeps duplicates or throws an exception only on certain data. These are the errors that show up most often in solutions to the tasks on this page.
| Mistake | What happens | How to fix it |
|---|---|---|
Calling list.remove(box) inside a for-each loop | Usually ConcurrentModificationException on the next iteration. But if you remove the second-to-last element, there is no exception: the loop just ends and the last element is never checked | Remove with iterator.remove() or removeIf() (Java 8) |
compareTo() compares only weight | TreeSet treats boxes of the same weight as equal and keeps only the first one | Compare more fields when the weights are equal, e.g. pass Comparator.comparingInt(HeavyBox::getWeight).thenComparingDouble(Box::getWidth) to the TreeSet constructor |
Your own class in a HashSet or as a HashMap key without equals() and hashCode() | Two identical students are stored twice, and contains() returns false for a copy | Override both methods (or use a record, Java 16+) |
Expecting insertion order from a HashMap | Books and pets are printed in an unpredictable order that can change when the table grows | LinkedHashMap for insertion order, TreeMap for keys sorted in their natural order |
union() written as set1.addAll(set2) | The method modifies the input set set1, so the next call to intersect() gives a wrong result | Work on a copy: Set<T> result = new HashSet<>(set1); |
Modifying a list created with List.of() or Arrays.asList() | UnsupportedOperationException on add()/remove() | Wrap it in a mutable list: new ArrayList<>(List.of(...)). Details are in the lesson Backed Collections |
Check your code
Declare variables by the interface type (List<HeavyBox> boxes = new ArrayList<>()), not by the implementation class, and never use raw types without <>. The rest of the style rules are in the code style checklist.
Frequently Asked Questions
Which Java collection should I use: List, Set, Queue or Map?
A List when order matters and duplicates are allowed (ArrayList by default). A Set when you need unique elements only: HashSet is the fastest, LinkedHashSet keeps insertion order, TreeSet keeps elements sorted. A Queue or Deque to process elements one by one or as a stack (ArrayDeque). A Map when you look up a value by its key. The collection each task on this page needs is in the table above.
What Java collections problems are asked in interviews?
The usual ones: remove duplicates from a list, find the intersection of two sets, remove elements while iterating without ConcurrentModificationException, sort objects with Comparable or Comparator, count word frequencies with a HashMap and build an LRU cache. The first four are practiced in the tasks on this page; the LRU cache is covered in the lesson LinkedHashMap.
Can I solve these exercises with the Stream API?
You can, but solve them with the plain collections API first: the point of the tasks is to practice Iterator, entrySet(), retainAll() and object comparison. A stream().filter() version is a good second solution to compare with, but it will not show you why removing inside a for-each loop ends with an exception.
In what order should I solve the tasks, and how long will they take?
The order follows the module lessons: ArrayList → TreeSet and HashSet → ArrayDeque → Iterator → HashMap → the Online Store part. One task takes 20–60 minutes, the whole page about 5.5 hours.
Comments