HashMap容器使用

  • Post author:
  • Post category:其他


package leetcode;

import com.sun.source.tree.Tree;

import java.util.*;
import java.util.function.BiConsumer;

class Solution {
    public String largestNumber(int[] nums) {
        Map<Integer,Double> map=new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
           if(nums[i]>=10){
               map.put(nums[i],nums[i]/10.0);
           }else{
               map.put(nums[i],nums[i]/1.0);
           }
        }
        System.out.println(map);
       /*hashmap容器遍历方法
        Iterator<Integer> iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            Integer key=iterator.next();
            Object val=map.get(key);
            System.out.println("key:"+key+"---"+"val:"+val);
        }*/
        List<Map.Entry<Integer,Double>> info=new ArrayList<Map.Entry<Integer,Double>>(map.entrySet());
        //排序前
        System.out.println("根据value值排序");
        System.out.println("排序前");
        for(int i=0;i<info.size();i++){
            String id=info.get(i).toString();
            System.out.println(id);
        }
        Collections.sort(info, new Comparator<Map.Entry<Integer, Double>>() {
            @Override
            public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) {
                return (int)(o2.getValue()-o1.getValue());
            }
        });
        //排序后
        String yasuo="";
        System.out.println("排序后");
        for(int i=0;i<info.size();i++){
            String id=info.get(i).toString();
            String a=info.get(i).getKey().toString();
            yasuo=yasuo+a;
            System.out.println(id);
        }
        System.out.println(yasuo);
       System.out.println("根据key值排序");
        Collections.sort(info, new Comparator<Map.Entry<Integer, Double>>() {
            @Override
            public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) {
                return (o2.getKey()-o1.getKey());
            }
        });
        for(int i=0;i<info.size();i++){
            String id=info.get(i).toString();
            System.out.println(id);
        }


        return "yasuo";
    }
}
/*



class StringComparator implements Comparator<String>
{
    public int compare(String a,String b)
    {
        return a.compareTo(b);
    }
}*/
class DoubleComparator implements Comparator<Double>{
    public int compare(Double a,Double b){
        return a.compareTo(b);
    }
}





版权声明:本文为m0_64468999原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。