Skip to content
Laviyx Learn

Try

Java Collections Practice

Practise ArrayList, HashMap, TreeMap, HashSet, queues and sorting with Comparator on real tasks.

Intermediate7 problemsUpdated

Review first: Collections Overview, ArrayList, HashMap and TreeMap, HashSet and TreeSet, Queue, Deque and PriorityQueue, Comparable, Comparator and Sorting

  1. 1.Word frequency

    Intermediate

    Count the words in "red blue red green blue red" and print the counts in alphabetical order.

    Show hint

    A TreeMap keeps keys sorted; merge(word, 1, Integer::sum) adds one per occurrence.

    Show solution
    Java
    import java.util.Map;
    import java.util.TreeMap;
    
    public class Main {
        public static void main(String[] args) {
            Map<String, Integer> counts = new TreeMap<>();
            for (String w : "red blue red green blue red".split(" ")) {
                counts.merge(w, 1, Integer::sum);
            }
            System.out.println(counts);
        }
    }
    Output
    {blue=2, green=1, red=3}
  2. 2.Remove duplicates, keep order

    Intermediate

    Remove the duplicates from List.of(4, 9, 4, 1, 9, 9, 7) while keeping the first-seen order.

    Show hint

    A LinkedHashSet keeps unique elements in insertion order.

    Show solution
    Java
    import java.util.ArrayList;
    import java.util.LinkedHashSet;
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            List<Integer> data = List.of(4, 9, 4, 1, 9, 9, 7);
            List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(data));
            System.out.println(unique);
        }
    }
    Output
    [4, 9, 1, 7]
  3. 3.Students in both clubs

    Intermediate

    Given Set.of("Asha", "John", "Meera", "Ravi") (chess) and Set.of("John", "Kiran", "Meera", "Priya") (music), print the students in both clubs and in either club, sorted.

    Show hint

    Copy into a TreeSet, then use retainAll for the intersection and addAll for the union.

    Show solution
    Java
    import java.util.Set;
    import java.util.TreeSet;
    
    public class Main {
        public static void main(String[] args) {
            Set<String> chess = Set.of("Asha", "John", "Meera", "Ravi");
            Set<String> music = Set.of("John", "Kiran", "Meera", "Priya");
    
            Set<String> both = new TreeSet<>(chess);
            both.retainAll(music);
            Set<String> either = new TreeSet<>(chess);
            either.addAll(music);
    
            System.out.println(both);
            System.out.println(either);
        }
    }
    Output
    [John, Meera]
    [Asha, John, Kiran, Meera, Priya, Ravi]
  4. 4.Sort by marks, then name

    Intermediate

    Sort the records Student("Ravi", 85), Student("Asha", 92), Student("Meera", 85), Student("John", 78) by marks from highest to lowest, with ties in alphabetical order, and print them.

    Show hint

    Comparator.comparingInt(Student::marks).reversed().thenComparing(Student::name).

    Show solution
    Java
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    
    record Student(String name, int marks) {}
    
    public class Main {
        public static void main(String[] args) {
            List<Student> students = new ArrayList<>(List.of(
                    new Student("Ravi", 85), new Student("Asha", 92),
                    new Student("Meera", 85), new Student("John", 78)));
    
            students.sort(Comparator.comparingInt(Student::marks).reversed()
                    .thenComparing(Student::name));
    
            for (Student s : students) {
                System.out.println(s.name() + " " + s.marks());
            }
        }
    }
    Output
    Asha 92
    Meera 85
    Ravi 85
    John 78
  5. 5.Group words by first letter

    Intermediate

    Group List.of("apple", "avocado", "banana", "blueberry", "cherry", "apricot") into a sorted map from first letter to the list of words.

    Show hint

    map.computeIfAbsent(letter, k -> new ArrayList<>()).add(word).

    Show solution
    Java
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.TreeMap;
    
    public class Main {
        public static void main(String[] args) {
            List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry", "apricot");
            Map<Character, List<String>> groups = new TreeMap<>();
            for (String w : words) {
                groups.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
            }
            System.out.println(groups);
        }
    }
    Output
    {a=[apple, avocado, apricot], b=[banana, blueberry], c=[cherry]}
  6. 6.Balanced brackets with a stack

    Intermediate

    Check whether "{[()]}", "([)]" and "(()" have balanced brackets, using an ArrayDeque as a stack.

    Show hint

    Push opening brackets; each closing bracket must match the popped top; the stack must be empty at the end.

    Show solution
    Java
    import java.util.ArrayDeque;
    import java.util.Deque;
    
    public class Main {
        static boolean balanced(String s) {
            Deque<Character> stack = new ArrayDeque<>();
            for (char c : s.toCharArray()) {
                if (c == '(' || c == '[' || c == '{') {
                    stack.push(c);
                } else {
                    char open = c == ')' ? '(' : c == ']' ? '[' : '{';
                    if (stack.isEmpty() || stack.pop() != open) return false;
                }
            }
            return stack.isEmpty();
        }
    
        public static void main(String[] args) {
            for (String s : new String[] {"{[()]}", "([)]", "(()"}) {
                System.out.println(s + " " + balanced(s));
            }
        }
    }
    Output
    {[()]} true
    ([)] false
    (() false
  7. 7.Top three with a priority queue

    Intermediate

    Print the three largest values of {12, 45, 7, 89, 23, 56, 34} from largest to smallest, using a PriorityQueue.

    Show hint

    new PriorityQueue<>(Collections.reverseOrder()) puts the largest element first; poll three times.

    Show solution
    Java
    import java.util.Collections;
    import java.util.PriorityQueue;
    
    public class Main {
        public static void main(String[] args) {
            PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
            for (int v : new int[] {12, 45, 7, 89, 23, 56, 34}) pq.offer(v);
    
            StringBuilder top = new StringBuilder();
            for (int i = 0; i < 3; i++) top.append(pq.poll()).append(' ');
            System.out.println(top.toString().trim());
        }
    }
    Output
    89 56 45