Skip to content
C

Collection Programs

Working with lists, sets, and maps hands-on is the best way to become comfortable with the Collection Framework for real projects and interviews.


Why practice these?

Working with lists, sets, and maps hands-on is the best way to become comfortable with the Collection Framework for real projects and interviews.

Program 1: Remove Duplicates from a List Using a Set

java
import java.util.*; public class RemoveDuplicates { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); Set<Integer> uniqueNumbers = new LinkedHashSet<>(numbers); System.out.println(uniqueNumbers); } }

Output:

[1, 2, 3, 4, 5]

Program 2: Count Word Frequency Using a Map

java
import java.util.*; public class WordFrequency { public static void main(String[] args) { String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"}; Map<String, Integer> frequency = new HashMap<>(); for (String word : words) { frequency.put(word, frequency.getOrDefault(word, 0) + 1); } System.out.println(frequency); } }

Output:

{banana=2, orange=1, apple=3}

Program 3: Sort a List of Names Alphabetically

java
import java.util.*; public class SortNames { public static void main(String[] args) { List<String> names = new ArrayList<>(Arrays.asList("Riya", "Aman", "Karan")); Collections.sort(names); System.out.println(names); } }

Output:

[Aman, Karan, Riya]

Key Points to Remember

  • getOrDefault() is a handy HashMap method for counting occurrences without extra null-checking code.
  • Converting a List into a Set is a quick, common way to remove duplicates.
  • Collections.sort() is the standard way to sort a List using its natural ordering.