1. Overview

In this tutorial, we’ll learn how to sort a LinkedHashMap based on its values. We’ll look at several approaches how to achieve it.

2. Sort With Conversion to List

The simplest way to sort a LinkedHashMap by values is to convert it into a list of key-value pairs. After that, we sort the list based on the values. Then, we create a new LinkedHashMap using the sorted list. Let’s have a look at an example:

@Test
fun `when given hashLinkedMap then it is sorted by values using list and sortedWith method`() {
    val ageOfStudents = linkedMapOf(
      "Mark" to 22,
      "Peter" to 23,
      "John" to 20
    )

    val sortedPairList = ageOfStudents.toList().sortedWith(compareBy { it.second })
    val result = linkedMapOf(*sortedPairList.toTypedArray())
    val expectedStudentsSortedByValues = linkedMapOf(
      "John" to 20,
      "Mark" to 22,
      "Peter" to 23
    )
    assertThat(result).isEqualTo(expectedStudentsSortedByValues)
}

In this example, we first create a LinkedHashMap with string keys and integer values. Then, we convert the map to a list of key-value pairs using the toList function. Next, we sort the list using the sortedWith() function and provide a comparator. Finally, we create a new LinkedHashMap using the sorted list. The output will be a LinkedHashMap sorted in ascending order based on the values.

It’s worth mentioning that we first converted the sorted list to an array, then used the spread operator (*) to convert the array to vararg to feed the linkedMapOf() builder function.

3. Sort Using the sortedby() Method

Alternatively, we can use the sortedBy() function instead of sortedWith() to simplify the sorting process. Here’s an example of how to implement this method:

@Test
fun `when given hashLinkedMap then it is sorted by values using sortedBy method`() {
    val ageOfStudents = linkedMapOf(
      "Mark" to 22,
      "Peter" to 23,
      "John" to 20
    )

    val sortedPairList = ageOfStudents.toList().sortedBy { it.second }
    val result = linkedMapOf(*sortedPairList.toTypedArray())
    val expectedStudentsSortedByValues = linkedMapOf(
      "John" to 20,
      "Mark" to 22,
      "Peter" to 23
    )
    assertThat(result).isEqualTo(expectedStudentsSortedByValues)
}

In this approach, we replace the sortedWith() function with sortedBy(). It allows us to specify the property to sort by directly. In this case, we sort the list based on the second element of each pair. Finally, the map is sorted in ascending order based on the values.

3. Conclusion

Sorting a LinkedHashMap by values requires more effort than sorting by keys. However, we can easily achieve the desired result with the methods demonstrated in this article.

As always, the source code of the examples is available over on GitHub.

2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!