首页 > 试题广场 >

对MAP进行排序

[编程题]对MAP进行排序
  • 热度指数:124 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
map是一种开发过程中经常使用的k-v数据结构,有个map保存了书名和书字数的关系,编写代码对map里面的书按照字数进行升序排序



输入描述:
第1行为map项的个数
第2到N行为k-v,以逗号分隔,值大小为int类型(不小于0)


输出描述:
输出map按照值升序排序后的结果
示例1

输入

4
a2,100
a1,100
b,300
c,200

输出

a2,100
a1,100
c,200
b,300

备注:
如果值相同的话需要按照输入顺序输出
    public static Map<String, Integer> sortMap(Map<String, Integer> map) {
        TreeMap<Integer, List<String>> treeMap = new TreeMap<>();
        map.entrySet().forEach(entry -> {
            List<String> indexList = treeMap.computeIfAbsent(entry.getValue(), k -> new ArrayList<>());
            indexList.add(entry.getKey());
        });
        Map<String, Integer> result = new ListOrderedMap();
        treeMap.entrySet().forEach(entry -> {
            entry.getValue().forEach(key -> result.put(key, map.get(key)));
        });
        return result;
    }

    public static Map<String, Integer> sortMap2(Map<String, Integer> map) {
        Map result = new ListOrderedMap();
        map.entrySet().stream().
                sorted(Map.Entry.comparingByValue()).
                forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue()));

        return result;
    }


原本用tree写,写一半发现Java8有工具方法🤯
编辑于 2021-01-29 20:36:23 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        String[] x=new String[20];
        String[] y=new String[2*a];
        String[] z=new String[20];
        String v =in.nextLine();
        for(int i=0;i<a;i++){
            String b =in.nextLine();
            x=b.split(",");
            y[2*i]=x[0];
            y[2*i+1]=x[1];
        }
        for(int i=0;i<a;i++){
            for(int j=i+1;j<a;j++){
                int q = Integer.parseInt(y[2*i+1]);
                int w = Integer.parseInt(y[2*j+1]);
                if(q>w){
                    z[0]=y[2*i];
                    y[2*i]=y[2*j];
                    y[2*j]=z[0];  
                    z[1]=y[2*i+1];
                    y[2*i+1]=y[2*j+1];
                    y[2*j+1]=z[1];
                }
            }
        }
        for(int i=0;i<a;i++){
           System.out.println(y[2*i]+","+y[2*i+1]);
        }
       
    }
}
发表于 2023-11-01 22:49:35 回复(0)