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

How to iterate a matrix. Matrix mental model.

row_column_indexes18831

Whenever I had to deal with matrices(bi-dimensional array), I had to struggle a bit how to iterate them.. you know the classic imbricated for loop from school …


for(int i=0; i<matrix.len; i++)
for(int j=0;... j++)

But here is my mental model which helps me better understand matrix iteration.

I think about a matrix is just like a ‘normal'(one-dimensional) array, whose elements are arrays themselves.
so in String[][] myMatrix the first part – String[] is the main array, and the second part [] refers to the array within(of) the main array

So, matrix[2][0] means – I want to access in the matrix the element at index 2(circled in red) – which gives me an array of String: String[3] subArray and from that row/subArray we get the element at index 0

Screenshot 2020-06-06 at 11.59.57

 How to iterate?

I) From Up to Down -> go to the i row
a[i] returns us the row(subArray) at index i

II) From Left to Right, -> in that row, go to the j element
a[][j] once we’re on the desired row, to j iterator returns us the desire element from the given row

How_to_Iterate_Matrix_20200606_102457__01__01

  for (int rowIdx = 0; rowIdx < matrix.length; rowIdx++) {
            T[] oneLine = matrix[rowIdx];
            for (int colIdx = 0; colIdx < oneLine.length; colIdx++) {
                oneLine[colIdx] = valProducer.apply(new RowColPair(rowIdx, colIdx));
            }
        }