Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 16 of 20 · 4 min read

Java maps and sorting

Java maps and sorting notes with examples: HashMap, LinkedHashMap and TreeMap, map methods, counting with merge, Comparable and Comparator.

What is a Map?

A Map stores key-value pairs: roll number to name, product code to price, word to count. Each key appears once; looking up a value by its key is fast.

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 120);
stock.put("notebook", 45);
stock.put("pen", 100);                  // same key: replaces 120
System.out.println(stock.get("pen"));   // 100
System.out.println(stock.get("ink"));   // null: no such key
System.out.println(stock.size());       // 2

Map methods

MethodDoes
put(k, v)add or replace
get(k)the value, or null
getOrDefault(k, d)the value, or d if missing
containsKey(k), containsValue(v)search
remove(k)delete a pair
putIfAbsent(k, v)add only if the key is new
merge(k, v, fn)add, or combine with the old value
keySet(), values(), entrySet()views for looping
Map.of(k1, v1, k2, v2)a small unmodifiable map

Looping over a map

for (Map.Entry<String, Integer> e : stock.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

for (String item : stock.keySet()) System.out.println(item);

stock.forEach((k, v) -> System.out.println(k + ": " + v));

Which map?

MapOrder of keysNotes
HashMapno guaranteed orderfastest; the default
LinkedHashMapthe order you inserted thempredictable output
TreeMapsorted by keyhas firstKey, lastKey, headMap, tailMap
Map<String, Integer> sorted = new java.util.TreeMap<>(stock);
System.out.println(sorted);   // {notebook=45, pen=100}

Counting with a map

The classic interview task: count how often each word appears.

public class WordCount {
    public static void main(String[] args) {
        String text = "to be or not to be";
        java.util.Map<String, Integer> count = new java.util.TreeMap<>();
        for (String w : text.split(" ")) {
            count.merge(w, 1, Integer::sum);
        }
        System.out.println(count);
    }
}
{be=2, not=1, or=1, to=2}

merge(w, 1, Integer::sum) puts 1 for a new word, or adds 1 to the old count. The longer equivalent is count.put(w, count.getOrDefault(w, 0) + 1);.

Grouping

Map<String, java.util.List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Ranchi", k -> new java.util.ArrayList<>()).add("Asha");
byCity.computeIfAbsent("Ranchi", k -> new java.util.ArrayList<>()).add("Ravi");
// {Ranchi=[Asha, Ravi]}

Sorting: Comparable

A class that implements Comparable<T> has a natural order, defined in compareTo:

class Student implements Comparable<Student> {
    String name;
    int marks;
    Student(String name, int marks) { this.name = name; this.marks = marks; }

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);      // alphabetical by name
    }

    @Override
    public String toString() { return name + "(" + marks + ")"; }
}

compareTo returns a negative number if this comes first, zero if equal, positive if it comes after. Collections.sort(list) and TreeSet use it.

Sorting: Comparator

A Comparator defines an order outside the class, so you can sort the same objects in many ways:

import java.util.*;

List<Student> list = new ArrayList<>(List.of(
    new Student("Ravi", 76), new Student("Asha", 91), new Student("Meena", 76)));

list.sort(Comparator.comparingInt(s -> s.marks));              // marks, low to high
list.sort(Comparator.comparingInt((Student s) -> s.marks).reversed());   // high to low
list.sort(Comparator.comparingInt((Student s) -> s.marks)
                    .reversed()
                    .thenComparing(s -> s.name));               // ties broken by name
System.out.println(list);   // [Asha(91), Meena(76), Ravi(76)]

Before Java 8 you wrote an anonymous class:

Collections.sort(list, new Comparator<Student>() {
    @Override
    public int compare(Student a, Student b) {
        return Integer.compare(a.marks, b.marks);
    }
});

Avoid return a.marks - b.marks; in a comparator: with very large or negative numbers the subtraction can overflow. Use Integer.compare.

Sorting a map by value

List<Map.Entry<String, Integer>> entries = new ArrayList<>(stock.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

Common mistakes

  • Expecting HashMap to print in insertion order; use LinkedHashMap.
  • Calling get on a missing key and unboxing the null into an int: NullPointerException. Use getOrDefault.
  • Using mutable objects as keys and changing them after insertion.
  • Keys of your own class without equals and hashCode.
  • Comparators that subtract numbers instead of using Integer.compare.

Key points

  • A Map stores unique keys, each with one value; put on an existing key replaces the value.
  • HashMap is fastest, LinkedHashMap keeps insertion order, TreeMap sorts by key.
  • Loop with entrySet(); count with merge or getOrDefault.
  • Comparable gives one natural order (compareTo); Comparator gives any number of orders.
  • Comparator.comparing(...).reversed().thenComparing(...) builds multi-level sorts.

Practice questions

1. What does this print? Map<String,Integer> m = new HashMap<>(); m.put("a",1); m.put("a",2); System.out.println(m.size() + " " + m.get("a"));

1 2. The second put replaces the value of the same key.

2. Count how many times each character appears in "banana".
Map<Character, Integer> freq = new TreeMap<>();
for (char c : "banana".toCharArray()) freq.merge(c, 1, Integer::sum);
System.out.println(freq);   // {a=3, b=1, n=2}
3. Which map keeps keys in alphabetical order?

TreeMap.

4. Sort a List<String> words by length, shortest first, and alphabetically when the lengths are equal.
words.sort(Comparator.comparingInt(String::length)
                     .thenComparing(Comparator.naturalOrder()));
5. When would you use a Comparator instead of Comparable?

When you need more than one order (by name, by marks, by date), or when you cannot change the class, such as a library class.