map的键值对的排序

package hash;
import java.util.*;
import java.util.Map.Entry;
public class MapSort {
    public static void main(String args[]){
    Map<Integer,Integer> map=new HashMap<Integer,Integer>();//定义一个hashMap
    map.put(8,3);
    map.put(1,2);
    map.put(3,4);
    map.put(5,7);
    map.put(4,6);
    map.put(9,8);
    //上面存进六个键值对
   
    //Map.Entry返回的是键值对的对象。下面这句话是把map键值对传到list集合中去了  


    List<Map.Entry<Integer, Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
//调用Collections工具类的sort方法,并重写比较方法。返回的是1就交换二者位置。
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
             public int compare(Map.Entry<Integer, Integer>m1,Map.Entry<Integer, Integer>m2){
            return m2.getKey()-m1.getKey();
             
}
});
    //第一种迭代方法。迭代器中传一个Map.Entry,这样输出的时候才能输出键值对。
//     Iterator<Map.Entry<Integer,Integer>> it=list.iterator();
//     while(it.hasNext()){
//     System.out.println(it.next());
//     }
    //ListIteractor暂时就这样用,原理还不懂
    ListIterator<Entry<Integer, Integer>> iteractor=list.listIterator();
    while(iteractor.hasNext()){
    System.out.println(iteractor.next());
    }
//     for(Iterator<Map.Entry<Integer,Integer>> it=list.iterator();it.hasNext();)
//     {
//     System.out.println(it.next());
//     }
    } 
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
默认情况下,map是按照键(key)的严格弱序关系(strict weak ordering)进行排序的。例如,如果map的键是整数类型,那么它们会按照从小到大的顺序进行排序。如果map的键是字符串类型,那么它们会按照字典序进行排序。 如果你想要按照其他方式进行排序,可以自定义比较函数(comparator)。比较函数是一个用于比较两个元素大小的函数,它接受两个元素作为参数,并返回一个bool值,表示它们的大小关系。 下面是一个例子,演示如何使用自定义比较函数对map进行排序: ```c++ #include <iostream> #include <map> #include <string> bool sortByValue(const std::pair<int, std::string>& a, const std::pair<int, std::string>& b) { return a.second < b.second; } int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}}; // 使用自定义比较函数进行排序 std::vector<std::pair<int, std::string>> vec(myMap.begin(), myMap.end()); std::sort(vec.begin(), vec.end(), sortByValue); // 输出排序结果 for (auto& pair : vec) { std::cout << pair.first << " " << pair.second << std::endl; } return 0; } ``` 在这个例子,我们定义了一个名为sortByValue的比较函数,用于按照值(value)的字典序进行排序。我们将map转换为一个vector,并使用std::sort函数和自定义比较函数进行排序。最后,我们遍历排序后的vector,并输出键和值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值