Deduplicate and Sort Math Scores
Introduction
This exercise deduplicates student math scores and prints them high to low—a common data-cleaning pattern. You will use HashSet for uniqueness, ArrayList / Collections for sorting, and skills from Arrays and Streams.
Prerequisites
Project Goal
Given scores (with duplicates):
- Remove duplicates
- Sort descending
- Print clear output
Example:
- Input:
[95, 88, 95, 76, 88, 92, 100, 76] - Output:
[100, 95, 92, 88, 76]
1) Prepare Sample Data
import java.util.ArrayList;
import java.util.List;
List<Integer> scores = new ArrayList<>(List.of(95, 88, 95, 76, 88, 92, 100, 76));
System.out.println("Original scores:");
System.out.println(scores);2) Deduplicate with HashSet
import java.util.HashSet;
import java.util.Set;
Set<Integer> uniqueSet = new HashSet<>(scores);
List<Integer> uniqueList = new ArrayList<>(uniqueSet);HashSet removes duplicates automatically. Iteration order is not defined—sorting fixes display order.
3) Sort High to Low
import java.util.Collections;
uniqueList.sort(Collections.reverseOrder());Alternative:
uniqueList.sort((a, b) -> Integer.compare(b, a));Stream style (Functional Programming):
import java.util.stream.Collectors;
List<Integer> sorted = scores.stream()
.distinct()
.sorted((a, b) -> Integer.compare(b, a))
.toList();4) Full Runnable Version
5) User Input Version
6) Enhanced Output with Grade Labels
static String gradeFor(int score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "D";
}
// when printing
for (int score : sorted) {
System.out.println(score + " (" + gradeFor(score) + ")");
}Surprise Challenge: Grade Statistics
After sorting:
- Count how many A, B, C, D grades
- Print average of unique scores
- Compare with Ranking Game medal idea for top 3 scores
Common Beginner Mistakes
Forgetting Descending Sort
Default sort is ascending—use reverseOrder() or reversed comparator.
Indexing a Set
Convert to List before get(i).
Skipping Validation
Reject scores outside 0–100 when reading input.
What’s Next
Enter advanced topics: Exception Handling.
FAQ
Why HashSet instead of manual duplicate removal?
Clear intent and efficient average-case performance.
Does distinct() in streams preserve order?
distinct() keeps encounter order; HashSet does not—choose tool to match requirement.
Arrays.sort vs Collections.sort?
Arrays.sort for arrays; Collections.sort / list.sort for lists. Ranking Game used Arrays.sort on arrays.
Can duplicates return after sorting?
No—dedup happens before sort in this pipeline.
LinkedHashSet use case?
Preserve first-seen order while removing duplicates, then sort a copy for ranking display.