Java中如何按键和值对HashMap进行排序

时间:2020-02-23 14:34:23  来源:igfitidea点击:

HashMap不保留元素的顺序,但如果要按键或者值对其进行排序。

在本教程中,我们将看到如何按键或者值对HashMap进行排序。

按键排序:

使用Treemap可以轻松完成按键排序。

我们只需将HashMap传递给Treemap的构造函数。

TreeMap map=new TreeMap(Map hm);

按值排序:

我们可以使用比较器按值对其进行排序。

按键排序示例:

创建Country.java如下。
它应该实现可比较的接口

package org.igi.theitroad;  
public class Country implements Comparable {  
  
 String name;  
 long population;  
   
 public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
@Override
public int compareTo(Object o) {
    Country country=(Country) o;
 return this.getName().compareTo(country.getName());
}  
       
}

创建TReeMAPCOMPMAIN.java如下:

package org.igi.theitroad;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
 
public class TreeMapCompMain {
 
 public static void main(String[] args)
 {
  Country Netherlands=new Country("Netherlands",1000);  
        Country japan=new Country("Japan",10000);  
            
        Country france=new Country("France",2000);  
        Country russia=new Country("Russia",20000);  
            
        HashMap<Country, String> countryCapitalMap=new HashMap<Country,String>();  
        countryCapitalMap.put(Netherlands,"Delhi");  
        countryCapitalMap.put(japan,"Tokyo");  
        countryCapitalMap.put(france,"Paris");  
        countryCapitalMap.put(russia,"Moscow");  
        
        System.out.println("Sorting HashMap by passing it to TreeMap constructor");
        TreeMap<Country,String> sortedTreeMapCountryCapital=new  TreeMap<Country,String> (countryCapitalMap);
        Iterator countryCapitalIter=sortedTreeMapCountryCapital.keySet().iterator();//put debug point at this line  
        while(countryCapitalIter.hasNext())  
        {  
            Country countryObj=countryCapitalIter.next();  
            String capital=countryCapitalMap.get(countryObj);  
            System.out.println(countryObj.getName()+"----"+capital);  
            }  
        }  
 
}

运行程序时,我们将得到以下输出:

Sorting HashMap by passing it to TreeMap constructor
France----Paris
Netherlands----Delhi
Japan----Tokyo
Russia----Moscow

按值排序示例:

其中我们将按值对HashMap进行排序。
其中我正在拍摄hashmap <string,string>以使示例更简单。
例子:

package org.igi.theitroad;
 
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
 
public class HashMapMain {
 
 public static void main(String args[]) {
  //HashMap with Country name as key and capital as value
  //HashMap stores elements in key value pairs
  HashMap<String, String> countryCapitalMap = new HashMap<String, String>();
 
  countryCapitalMap.put("Japan", "Tokyo");
  countryCapitalMap.put("France", "Paris");
  countryCapitalMap.put("Russia", "Moscow");
  countryCapitalMap.put("Netherlands", "Delhi");
 
  System.out.println("-----------------------------");
  //Iterating HashMap Using keySet() and for each loop
  System.out.println("Before Sorting");
  System.out.println("-----------------------------");
  for (String countryKey : countryCapitalMap.keySet()) {
   System.out.println("Country:" + countryKey + " and  Capital:" + countryCapitalMap.get(countryKey));
 
  }
  
  Set<Entry<String, String>> countryCapitalEntrySet=countryCapitalMap.entrySet();
  
  List<Entry<String, String>> entryList=new ArrayList<Entry<String, String>>(countryCapitalEntrySet);
  
  Collections.sort(entryList,new Comparator<Entry<String,String>>() {
 
   @Override
   public int compare(Entry<String,String> o1, Entry<String,String> o2) {
    return o1.getValue().compareTo(o2.getValue());
   }
  });
  System.out.println("-----------------------------");
     
  //Using LinkedHashMop to keep entries in sorted order
  LinkedHashMap<String,String> sortedHashMap=new LinkedHashMap<String,String>();
  for (Entry<String,String> entry:entryList) {
   sortedHashMap.put(entry.getKey(), entry.getValue());
  }
  
  System.out.println("After Sorting");
  System.out.println("-----------------------------");
  //Iterating sortedHashMap Using keySet() and for each loop
  
  for (String countryKey : sortedHashMap.keySet()) {
   System.out.println("Country:" + countryKey + " and  Capital:" + sortedHashMap.get(countryKey));
 
  }
 }
}

运行上面的程序时,我们将得到以下输出

----------------------------
Before Sorting
----------------------------
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:Netherlands and  Capital:Delhi
----------------------------
After Sorting
----------------------------
Country:Netherlands and  Capital:Delhi
Country:Russia and  Capital:Moscow
Country:France and  Capital:Paris
Country:Japan and  Capital:Tokyo