sortedMapOf
Returns a new SortedMap with the specified contents, given as a list of pairs where the first value is the key and the second is the value.
The resulting SortedMap determines the equality and order of keys according to their natural sorting order.
import kotlin.test.* import java.util.* fun main(args: ArrayString>) < //sampleStart val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("d", 1)) println(map.keys) // [b, c, d] println(map.values) // [2, 3, 1] //sampleEnd >
fun sortedMapOf( comparator: Comparatorin K>, vararg pairs: PairK, V> ): SortedMap
Returns a new SortedMap with the specified contents, given as a list of pairs where the first value is the key and the second is the value.
The resulting SortedMap determines the equality and order of keys according to the sorting order provided by the given comparator.
import kotlin.test.* import java.util.* fun main(args: ArrayString>) < //sampleStart val map = sortedMapOf(compareBy < it.length >.thenBy < it >, Pair("abc", 1), Pair("c", 3), Pair("bd", 4), Pair("bc", 2)) println(map.keys) // [c, bc, bd, abc] println(map.values) // [3, 2, 4, 1] //sampleEnd >
Kotlin 1.7
Returns a list of all elements sorted descending according natural order the value returned by specified selector function.
How to sort a kotlin map by value
Kotlin map is used to hold key-value pairs and using a key, we can access the value that is linked with it. keys in a Kotlin map are unique. We can’t have two same keys. In this post, we will learn how to sort a Kotlin map by its values.
The program will create one map with some key-value pairs and it will sort them by its values.
Method 1: sort a map by values by converting it to a list:
Below is the complete program:
fun main() val givenMap = hashMapOfString, Int>() givenMap["one"] = 1 givenMap["two"] = 2 givenMap["three"] = 3 givenMap["four"] = 4 givenMap["five"] = 5 givenMap["six"] = 6 println("Given map :") givenMap.forEach (k, v) -> println("$k => $v") > val sortedMap = givenMap.toList().sortedBy (k, v) -> v >.toMap() println("Sorted map :") sortedMap.forEach (k, v) -> println("$k => $v") > >
Here, we have created one hashMap with String as key and Int as the value. givenMap is that variable. We inserted couple of values to this map and printed its key-values using a forEach.
Then we sorted this map by changing it to a list and with the help of sortedBy. The sorted list is converted back to a map using toMap.
This program prints the below output:
: six => 6 four => 4 one => 1 two => 2 three => 3 five => 5 Sorted map : one => 1 two => 2 three => 3 four => 4 five => 5 six => 6
Method 2: Using sortedBy on entries fo the map:
We can use sortedBy method on the entries of the given map. It will sort the pairs based on values if we provide it.value in sortedBy method. These values can be put in a LinkedHashMap :
fun main() val givenMap = hashMapOfString, Int>() givenMap["one"] = 1 givenMap["two"] = 2 givenMap["three"] = 3 givenMap["four"] = 4 givenMap["five"] = 5 givenMap["six"] = 6 println("Given map :") givenMap.forEach (k, v) -> println("$k => $v") > var sortedMap: MutableMapString,Int> = LinkedHashMap() givenMap.entries.sortedBy it.value >.forEachsortedMap[it.key] = it.value> println("Sorted map :") sortedMap.forEach (k, v) -> println("$k => $v") > >
It will print similar result:
: six => 6 four => 4 one => 1 two => 2 three => 3 five => 5 Sorted map : one => 1 two => 2 three => 3 four => 4 five => 5 six => 6
Method 3: Using entries.sortedWith :
This is almost similar to the above example. The only difference is that we are using sortedWith to sort the items:
fun main() val givenMap = hashMapOfString, Int>() givenMap["one"] = 1 givenMap["two"] = 2 givenMap["three"] = 3 givenMap["four"] = 4 givenMap["five"] = 5 givenMap["six"] = 6 println("Given map :") givenMap.forEach (k, v) -> println("$k => $v") > var sortedMap: MutableMapString,Int> = LinkedHashMap() givenMap.entries.sortedWith(java.util.Map.Entry.comparingByValue()).forEachsortedMap[it.key] = it.value> println("Sorted map :") sortedMap.forEach (k, v) -> println("$k => $v") > >
: six => 6 four => 4 one => 1 two => 2 three => 3 five => 5 Sorted map : one => 1 two => 2 three => 3 four => 4 five => 5 six => 6
Kotlin sort map by key
The sample code is as follows:
fun main() val map = sortedMapOf(1 to 2, 3 to 1, 2 to 3) println(map) // Output: println(map.javaClass.simpleName) // Output: TreeMap >
As can be seen from the above example, the implementation class of an orderly MAP is TreeMap, which defaults to be sorted ascending to KEY. A comparator can be received in the construction method of TreeMap, which is used to compare Key, so if we want to descend, you can implement it through the incoming comparator, the code is as follows:
fun main() val comparator = kotlin.Comparator key1: Int, key2: Int -> key2.compareTo(key1) > val map = TreeMapInt, Int>(comparator) map[1] = 2 map[3] = 1 map[2] = 3 println(map) // Output: >
OK, the above code achieves descending order sorting of Key. But sometimes, our sorting requires Value’s participation, such as the following data structure:
/ ** Employee * / data class Employee(val name: String, val isOnline: Boolean)
As the above is an employee, a name attribute, and online status properties, such as a chat software, when logging in is online, offline is offline.
We can use a list to represent all the employees of a department, you can use a map to represent all the employees of a company multiple departments, and the code examples are as follows:
fun main() val R & D staff list = listOf(Employee("01 R & D Department Zhang Mou", false), Employee("01 R & D" Wang Mou ", false)) val Sales staff list = listOf(Employee("02 Sales Department Chen Moumou", true), Employee("02 Sales Department Li Moumou", false)) val List of after-sales staff = listOf(Employee("03 after-sales department Zhou Moumou", false), Employee("03 after-sales department Zhao Moumou", true)) val company = TreeMapString, ListEmployee>>() company["01 R & D Department"] = R & D staff list company["02 Sales"] = Sales staff list company["03 after-sales"] = List of after-sales staff company.forEach key, value -> println(key) > >
The print results are as follows:
01R & D department 02Sales 03After-sales
It is printed here that the department’s name can be seen that the default is sorted by the department name. At this time, I want to sort the department according to the online state, and the department of the online state employee is in front, as in the three departments, the R & D department There is no online person, so the R & D department should be ranked in the end. At this time, use KEY to do the sorting conditions. It is no longer able to meet our needs, and the Comparator object can only sort the key, how do you implement it using Value? A: Customize the sorting method of TreeMap, but the source code is found, the Compare method is final type, can’t overwrite, oh, it seems that the Treemap can not be sorted by Key unless we use the value of Value. Bind to Key, but in this case, we are not as good as direct use of list, add a departmental class, implement the following:
/ ** Employee * / data class Employee(val name: String, val isOnline: Boolean) / ** Department-based * / data class Department(val name: String, val employeeList: ListEmployee>)
The Department here is equivalent to the TreeMap class, the name property corresponds to the TreeMap’s key, the EmployeeList property corresponds to the TreeMap’s value, and then we save multiple departments to the list, so you can sort the List, you can use it To the employee list object, the implementation code is as follows:
fun main() val R & D staff list = mutableListOf(Employee("01 R & D Department Zhang Mou", false), Employee("01 R & D" Wang Mou ", false)) val Sales staff list = mutableListOf(Employee("02 Sales Department Chen Moumou", true), Employee("02 Sales Department Li Moumou", false)) val List of after-sales staff = mutableListOf(Employee("03 after-sales department Zhou Moumou", false), Employee("03 after-sales department Zhao Moumou", true)) val R & D department = Department("01 R & D Department", R & D staff list) val Sales = Department("02 Sales", Sales staff list) val After-sales = Department("03 after-sales", List of after-sales staff) val company = mutableListOf(R & D department, Sales, After-sales) / / Sort each department's list of personnel, front of the line, back from the line company.forEach department -> department.employeeList.sortByDescending it.isOnline > > // Sort by the department, the front of the department in the online state company.sortByDescending department -> department.employeeList[0].isOnline > company.forEach println(it) > >
Department(name=02Sales, employeeList=[Employee(name=02Sales, isOnline=true), Employee(name=02Li Moumou, Sales, isOnline=false)]) Department(name=03After-sales, employeeList=[Employee(name=03After-sales department Zhao Moumou, isOnline=true), Employee(name=03After-sales, Zhou Moumou, isOnline=false)]) Department(name=01R & D department, employeeList=[Employee(name=01R & D department Zhang Mou, isOnline=false), Employee(name=01R & D Wang Moumou, isOnline=false)])
For sorting, more logic can also be added, such as employees having the same online state, sorted by employee names, the same departments in the line status, sorting the department name, assuming that we want to implement the same, use name s sequence, implement code as follows:
company.forEach department -> department.employeeList.sortWith(Comparator employee1, employee2 -> if (employee1.isOnline != employee2.isOnline) // The state is different, then sorted in descending order (i.e., the front of the online row) employee2.isOnline.compareTo(employee1.isOnline) > else // State the same, order sequentially employee1.name.compareTo(employee2.name) > >) > // Sort by the department, the front of the department in the online state company.sortWith(kotlin.Comparator department1, department2 -> if (department1.employeeList[0].isOnline != department2.employeeList[0].isOnline) / department2.employeeList[0].isOnline.compareTo(department1.employeeList[0].isOnline) > else // State the same, order sequentially sequentially according to the department name department1.name.compareTo(department2.name) > >)
Department(name=02Sales, employeeList=[Employee(name=02Sales, isOnline=true), Employee(name=02Li Moumou, Sales, isOnline=false)]) Department(name=03After-sales, employeeList=[Employee(name=03After-sales department Zhao Moumou, isOnline=true), Employee(name=03After-sales, Zhou Moumou, isOnline=false)]) Department(name=01R & D department, employeeList=[Employee(name=01R & D department Zhang Mou, isOnline=false), Employee(name=01R & D Wang Moumou, isOnline=false)])
For more detailed sorting for LIST, you can view this article:List in kotlin
toSortedMap
Converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to their natural sorting order.
Note that if the natural sorting order of keys considers any two keys of this map equal (this could happen if the equality of keys according to Comparable.compareTo is inconsistent with the equality according to Any.equals), only the value associated with the last of them gets into the resulting map.
import kotlin.test.* import java.util.* fun main(args: ArrayString>) < //sampleStart val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("d", 1)) val sorted = map.toSortedMap() println(sorted.keys) // [b, c, d] println(sorted.values) // [2, 3, 1] //sampleEnd >
fun Map .toSortedMap( comparator: Comparatorin K> ): SortedMap
Converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to the sorting order provided by the given comparator.
Note that if the comparator considers any two keys of this map equal, only the value associated with the last of them gets into the resulting map.
import kotlin.test.* import java.util.* fun main(args: ArrayString>) < //sampleStart val map = mapOf(Pair("abc", 1), Pair("c", 3), Pair("bd", 4), Pair("bc", 2)) val sorted = map.toSortedMap(compareBy < it.length >.thenBy < it >) println(sorted.keys) // [c, bc, bd, abc] //sampleEnd >
Kotlin 1.7
Returns an array of Short containing all the elements this generic Returns an array of Short containing all the elements this collection.