Java教程

Java中对HashMap进行排序

Java HashMap默认情况下不保留任何顺序。如果需要对HashMap进行排序,我们将根据需求对其进行显式排序。 Java提供了一个根据键和值对HashMap进行排序的选项。在本节中,我们将学习如何根据键和值对HashMap进行排序。
按键排序HashMap</span> 按值对HashMap排序

按键对HashMap进行排序

有以下几种按键对HashMap进行排序的方法:
使用 TreeMap</strong> 通过使用 LinkedHashMap</strong>
使用LinkedHashMap时,应遵循以下过程:
使用LinkedHashMap时,需要获取密钥集。将Set转换为List,对列表进行排序,然后以相同顺序将排序后的列表添加到LinkedHashMap中。我们在示例 按值对HashMap排序中完成的过程相同。
按键对HashMap排序的示例
在下面的示例中,我们使用TreeMap构造函数对元素进行排序,并将HashMap类的对象作为参数传递。这是按键对HashMap进行排序的最简单方法。
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Iterator;
public class SortHashMapByKeys
{
    public static void main(String args[])
{
        HashMap<Integer, String> hm=new HashMap<Integer, String>();
        hm.put(23, "Yash");
        hm.put(17, "Arun");
        hm.put(15, "Swarit");
        hm.put(9, "Neelesh");
        Iterator <Integer> it = hm.keySet().iterator();
        System.out.println("Before Sorting");
        while(it.hasNext()){
            int key=(int)it.next();
            System.out.println("Roll no: "+key+" name: "+hm.get(key));
        }
        System.out.println("\n");
        Map<Integer, String> map=new HashMap<Integer, String>();
        System.out.println("After Sorting");
        TreeMap<Integer,String> tm=new TreeMap<Integer,String>(hm);
        Iterator itr=tm.keySet().iterator();
        while(itr.hasNext()) {
            int key=(int)itr.next();
            System.out.println("Roll no: "+key+" name: "+hm.get(key));
        }
    }
}
输出:
Before Sorting
Roll no: 17 name: Arun
Roll no: 23 name: Yash
Roll no: 9 name: Neelesh
Roll no: 15 name: Swarit
After Sorting
Roll no: 9 name: Neelesh
Roll no: 15 name: Swarit
Roll no: 17 name: Arun
Roll no: 23 name: Yash

使用Comparator接口按值对HashMap进行排序

在Java中,按值对HashMap进行排序很复杂,因为没有可用的直接方法。要按值对HashMap进行排序,我们需要创建一个 比较器。它根据值比较两个元素。
然后从Map中获取Set元素并将Set转换为List。使用 Collections.sort(List)方法通过传递自定义比较器按值对元素列表进行排序。现在创建一个新的 LinkedHashMap</strong>并将已排序的元素复制到其中。由于 LinkedHashMap</strong>保证了映射的插入顺序。我们得到了一个HashMap,其值是按顺序排序的。
按Keys和Values对HashMap进行排序之间存在细微的区别,即它可以有重复的值,但不能有重复的Key。我们无法使用TreeMap对值进行排序,因为TreeMap按键对元素进行排序。
按值对HashMap进行排序的示例
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SortHashMapValue {
    public static void main(String[] args) {
        HashMap<Integer, String> hm = new HashMap<Integer, String>();
        hm.put(6, "Tushar");
        hm.put(12, "Ashu");
        hm.put(5, "Zoya");
        hm.put(78, "Yash");
        hm.put(10, "Praveen");
        hm.put(67, "Boby");
        hm.put(1, "Ritesh");
        System.out.println("Before Sorting:");
        Set set = hm.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry map = (Map.Entry)iterator.next();
            System.out.println("Roll no: "+map.getKey()+" Name: "+map.getValue());
        }
        Map<Integer, String> map = sortValues(hm);
        System.out.println("\n");
        System.out.println("After Sorting:");
        Set set2 = map.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry me2 = (Map.Entry)iterator2.next();
            System.out.println("Roll no: "+me2.getKey()+" Name: "+me2.getValue());
        }
    }
    private static HashMap sortValues(HashMap map) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
            }
        });
        HashMap sortedHashMap = new LinkedHashMap();
        for (Iterator it = list.iterator();
        it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            sortedHashMap.put(entry.getKey(), entry.getValue());
        }
        return sortedHashMap;
    }
}
输出:
Before Sorting:
Roll no: 1 Name: Ritesh
Roll no: 67 Name: Boby
Roll no: 5 Name: Zoya
Roll no: 6 Name: Tushar
Roll no: 10 Name: Praveen
Roll no: 12 Name: Ashu
Roll no: 78 Name: Yash
After Sorting:
Roll no: 12 Name: Ashu
Roll no: 67 Name: Boby
Roll no: 10 Name: Praveen
Roll no: 1 Name: Ritesh
Roll no: 6 Name: Tushar
Roll no: 78 Name: Yash
Roll no: 5 Name: Zoya

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4