PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How can i sort HashMap<String,Int> order by their values in Kotlin?

 September 20, 2022     hashmap, kotlin, list, sorting, treemap     No comments   

Issue

Here is my example, how can i do that in Kotlin?

var hashMapForTry = HashMap<String,Int>()

hashMapForTry.put("Hi",5)
hashMapForTry.put("What",7)
hashMapForTry.put("How",2)
hashMapForTry.put("Go",1)
hashMapForTry.put("Ford",9)

Solution

You cannot sort a HashMap because it doesn't guarantee that its entries will be iterated in any particular order. You can, however, arrange the items into a LinkedHashMap which keeps the insertion order:

    val resultMap = hashMapForTry.entries.sortedBy { it.value }.associate { it.toPair() }

    println(resultMap)

Here the entries of hashMapForTry are sorted by entry value, then associate function converts the list of entries into a map that preserves the order of entries from that list.

The result type of this function is Map<String, Int>. If you need to mutate the result further, you can use associateTo function and specify an empty destination LinkedHashMap as a parameter:

....associateTo(LinkedHashMap()) { ... }


Answered By - Ilya
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing