码迷,mamicode.com
首页 > 编程语言 > 详细

201503-2 数字排序 Java

时间:2020-02-21 22:25:40      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:hashmap   ati   arraylist   temp   int()   put   turn   tin   java   

技术图片

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<n;i++) {
            int temp = sc.nextInt();
            if(map.containsKey(temp)) {
                map.replace(temp,map.get(temp)+1);
            }else {
                map.put(temp, 1);
            }
        }
        //需要按照map的value排序。先转成List,再sort
        List<Map.Entry<Integer, Integer>> list= new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
        list.sort(new Comparator<Map.Entry<Integer, Integer>>() {
            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        for (Map.Entry<Integer, Integer> entry : list) {
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
    }
}

201503-2 数字排序 Java

标签:hashmap   ati   arraylist   temp   int()   put   turn   tin   java   

原文地址:https://www.cnblogs.com/yu-jiawei/p/12343217.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!