如何对HashMap按键值排序
Java中HashMap是一种用于存储“键”和“值”信息对的数据结构。不同于Array、ArrayList和LinkedLists,它不会维持插入元素的顺序。
因此,在键或值的基础上排序HashMap是一个很难的面试问题,如果你不知道如何解决的话。下面让我们看看如何解决这个问题。
1. HashMap存储每对键和值作为一个Entry<K,V>对象。例如,给出一个HashMap,
Map<String,Integer> aMap = new HashMap<String,Integer>();
键的每次插入,都会有值对应到散列映射上,生成一个Entry <K,V>对象。通过使用这个Entry <K,V>对象,我们可以根据值来排序HashMap。
2.创建一个简单的HashMap,并插入一些键和值。
ap<String,Integer> aMap = new HashMap<String,Integer>(); // adding keys and values
aMap.put("Five", 5);
aMap.put("Seven", 7);
aMap.put("Eight", 8);
aMap.put("One",1);
aMap.put("Two",2);
aMap.put("Three", 3);
3.从HashMap恢复entry集合,如下所示。
Set<Entry<String,Integer>> mapEntries = aMap.entrySet();
4.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题。我们之所以要使用链表来实现这个目的,是因为在链表中插入元素比数组列表更快。
List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);
5.通过传递链表和自定义比较器来使用Collections.sort()方法排序链表。
Collections.sort(aList, new Comparator<Entry<String,Integer>>() {
@Override
public int compare(Entry<String, Integer> ele1,
Entry<String, Integer> ele2) {
return ele1.getValue().compareTo(ele2.getValue());
}
});
6.使用自定义比较器,基于entry的值(Entry.getValue()),来排序链表。
7. ele1.getValue(). compareTo(ele2.getValue())——比较这两个值,返回0——如果这两个值完全相同的话;返回1——如果第一个值大于第二个值;返回-1——如果第一个值小于第二个值。
8. Collections.sort()是一个内置方法,仅排序值的列表。它在Collections类中重载。这两种个方法是
public static <T extends Comparable<? super T>> void sort(List<T> list) public static <T> void sort(List<T> list, Comparator<? super T> c)
9.现在你已经排序链表,我们需要存储键和值信息对到新的映射中。由于HashMap不保持顺序,因此我们要使用LinkedHashMap。
// Storing the list into Linked HashMap to preserve the order of insertion.
Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();
for(Entry<String,Integer> entry: aList) {
aMap2.put(entry.getKey(), entry.getValue());
}
10.完整的代码如下。
package com.speakingcs.maps; import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class SortMapByValues { public static void main(String[] args) { Map<String,Integer> aMap = new HashMap<String,Integer>(); // adding keys and values
aMap.put("Five", 5);
aMap.put("Seven", 7);
aMap.put("Eight", 8);
aMap.put("One",1);
aMap.put("Two",2);
aMap.put("Three", 3); sortMapByValues(aMap); } private static void sortMapByValues(Map<String, Integer> aMap) { Set<Entry<String,Integer>> mapEntries = aMap.entrySet(); System.out.println("Values and Keys before sorting ");
for(Entry<String,Integer> entry : mapEntries) {
System.out.println(entry.getValue() + " - "+ entry.getKey());
} // used linked list to sort, because insertion of elements in linked list is faster than an array list.
List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries); // sorting the List
Collections.sort(aList, new Comparator<Entry<String,Integer>>() { @Override
public int compare(Entry<String, Integer> ele1,
Entry<String, Integer> ele2) { return ele1.getValue().compareTo(ele2.getValue());
}
}); // Storing the list into Linked HashMap to preserve the order of insertion.
Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();
for(Entry<String,Integer> entry: aList) {
aMap2.put(entry.getKey(), entry.getValue());
} // printing values after soring of map
System.out.println("Value " + " - " + "Key");
for(Entry<String,Integer> entry : aMap2.entrySet()) {
System.out.println(entry.getValue() + " - " + entry.getKey());
} }
}
如何对HashMap按键值排序的更多相关文章
- Java面试题:如何对HashMap按键值排序
Java中HashMap是一种用于存储“键”和“值”信息对的数据结构.不同于Array.ArrayList和LinkedLists,它不会维持插入元素的顺序. 因此,在键或值的基础上排序HashMap ...
- java算法面试题:有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数 按值的降序排序,如果值相同则按键值的字母顺序
package com.swift; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; publi ...
- HashMap按键排序和按值排序
对map集合进行排序 今天做统计时需要对X轴的地区按照地区代码(areaCode)进行排序,由于在构建XMLData使用的map来进行数据统计的,所以在统计过程中就需要对map进行排序. 一.简单 ...
- TreeMap/LinkedHashMap/HashMap按键排序和按值排序
今天做统计时需要对X轴的地区按照地区代码(areaCode)进行排序,由于在构建XMLData使用的map来进行数据统计的,所以在统计过程中就需要对map进行排序. 一.简单介绍Map 在讲解Map排 ...
- Java Map按键(Key)排序和按值(Value)排序
Map排序的方式有很多种,两种比较常用的方式:按键排序(sort by key), 按值排序(sort by value).1.按键排序jdk内置的java.util包下的TreeMap<K,V ...
- Python dict 按键和值排序
python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行:1 下面的是按照value的值从大到小的顺序来排序. ...
- java -- 对Map按键排序、按值排序
java -- 对Map按键.按值排序 1.按键排序(sort by key) 直接上代码 ↓ public Map<String, Str ...
- 160725、Java Map按键排序和按值排序
按键排序(sort by key) jdk内置的Java.util包下的TreeMap<K,V>既可满足此类需求,原理很简单,其重载的构造器之一 有一个参数,该参数接受一个比较器,比较器定 ...
- python 字典(dict)按键和值排序
python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行: 1 下面的是按照value的值从大到小的顺序来排序 ...
随机推荐
- JMeter学习-015-JMeter 断言之-Bean Shell Assertion
前面的博文中有对 JMeter 中的 响应断言 进行了讲解并实例演示,详情敬请参阅博文:JMeter学习-007-JMeter 断言实例之一 - 响应断言. 在 JMeter 中总计提供了如下几种 B ...
- c#设计模式之单例模式
单例模式(Singleton Pattern )就是为了整个应用程序的生命周期内的任何时刻,类只能创建一个实例. 单线程下的单例模式代码: public class Singleton { priva ...
- 1.后台如何获取 jquery get方式的ajax的参数
1. update.jsp 1.2 默认是dataType是json getJSON: function( url, data, callback ) { return jQuery.get(url, ...
- Insert BLOB && CLOB from PL/SQL and JDBC
For PL/SQL 1)Create Directory Where BLOB resides. create or replace directory temp as '/oradata2'; - ...
- Docker容器管理
容器是Docker第二个核心概念,简单的的说容器是镜像的一个运行实例,所不同的是,它带有额外的可写文件层. 如果说虚拟机是模拟运行了一整套操作系统(提供运行态环境和其他系统环境)和跑在上面的应用.那么 ...
- linux的5个查找命令_转
转自:http://www.ruanyifeng.com/blog/2009/10/5_ways_to_search_for_files_using_the_terminal.html 在Linux中 ...
- selenium 基本了解
Selenium的界面 白色:还未执行 浅青色:动作成功 深青色:判断成功 浅粉红色:判断失败,但不影响测试案例的运行 深粉红色:判断失败,且测试案例无法正常运行 Command 存在的命令 Acti ...
- iOS Reachability的基本用法
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @pr ...
- mysql在线改表结构 pt-online-schema-change
https://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html 不锁表更改数据库表结构 pt-online-s ...
- HTML--表单,图片热点,网页划区和拼接
一.图片热点 规划出图片上的一个区域,可以做出超链接,直接点击图片区域就可以完成跳转的效果. 示例: <img src="/ usemap="longzhu"> ...