TreeMap vs. LikedHashMap

If it was a bit of a hustle to understand/remember the difference between the 2 implementations, here is a small example that clicked for me

Let’s take the problem of counting the Letters occurrences in a given word. And say we want to count letters repetitions in the word ‘elephant

Map<Character, Integer> letterToLetterCount

 for (Character character : wordLetters) {
            letterToLetterCount.compute(character, (key, val) -> val == null ? 1 : val + 1);
        }
return letterToLetterCount;
letterToLetterCount = new LinkedHashMap<>();
//{e=2, l=1, p=1, h=1, a=1, n=1, t=1}

letterToLetterCount = new TreeMap<>();
//{a=1, e=2, h=1, l=1, n=1, p=1, t=1}

LinkedHashMap – Map’s Keys Insertion Order is preserved

TreeMap – Map’s Keys are sorted by their natural order

Leave a comment