前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Sort HashMap By key and By value

Sort HashMap By key and By value

作者头像
用户7037180
修改2020-11-23 10:49:27
5790
修改2020-11-23 10:49:27
举报
文章被收录于专栏:aryank4564

In this article, we are going to have look at how to sort HashMap by key and to sort HashMap by value in Java. We are going to learn different approaches to sort HashMap.

Visit this link to read the full article: https://www.java8net.com/2020/02/sort-hashmap-by-key-and-by-value.html

HashMap does not sort its key-value pair and also it does not maintain any order (neither insertion nor sorted). If we want to sort HashMap then we need to provide custom logic that can sort HashMap and sort HashMap by key we can use either TreeMap or LinkedHashMap but in the case of sort HashMap by value, we have the only option of LinkedHashMap as TreeMap cannot be used to sort HashMap by value. To sort HashMap by key, we can use the TreeMap class. TreeMap in java is used to store key-value pairs and sort all the pairs w.r.t. keys. We can create a TreeMap from the HashMap and TreeMap sort HashMap by key.

Steps to sort HashMap by key using TreeMap

  1. Create a Comparator, which provides logic to sort HashMap by key.
  2. Create a TreeMap using Comparator.
  3. Add all the entries of HashMap into the TreeMap

Java Sort HashMap Example HashMap hashMap = new HashMap<>(); hashMap.put("Programming In Java", 450); hashMap.put("Introduction to Algorithms", 800); hashMap.put("Data Structures", 600); hashMap.put("Learn C++", 350); System.out.println("-----------Before Sorting--------------"); Set> unsortedEntrySet = hashMap.entrySet(); for (Entry entry : unsortedEntrySet) { System.out.println(entry.getKey() + " = " + entry.getValue()); }

Comparator keyComparator = (s1, s2) -> s1.compareTo(s2); TreeMap treeMap = new TreeMap<>(keyComparator); treeMap.putAll(hashMap); System.out.println("-----------After Sorting---------------"); Set> sortedEntrySet = treeMap.entrySet(); for (Entry entry : sortedEntrySet) { System.out.println(entry.getKey() + " = " + entry.getValue()); }

Visit this link to read the full article: https://www.java8net.com/2020/02/sort-hashmap-by-key-and-by-value.html

Further Learning: https://www.java8net.com/2020/02/how-to-sort-arraylist-in-java.html https://www.java8net.com/2020/02/treemap-in-java.html https://www.java8net.com/2020/03/java-optional.html https://www.java8net.com/2020/01/lambda-expression-java.html https://www.java8net.com/2020/01/functional-interface-in-java.html

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档