JAVA中的map怎么根据值排序

map集合是有3个元素,{苹果,价格=50},{华为,价格=80},{vivo,价格=30},这怎么排序,求daima
想要的效果打印{华为,价格=80},{苹果,结果=50},{vivo,价格=30}

public static void main(String[] args) {
    Map<String, Integer> maps = new HashMap<>();
    maps.put("iphone",50);
    maps.put("hua_wei",80);
    maps.put("vivo",30);
    LinkedList<Map.Entry<String, Integer>> list = new LinkedList<>(maps.entrySet());
    Comparator<Map.Entry<String, Integer>> comparator = Comparator.comparing(Map.Entry::getValue);Collections.sort(list, comparator.reversed());
    list.stream().forEach(t->{
        System.out.println(t.getKey()+":"+t.getValue());
    });
}

hashmap不排序,采用LinkedHashMap可以进行排序,默认按照元素插入顺序排序

你给的map格式明显是有问题的,我按我的理解给一种解决方案,你参考一下:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Test {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("苹果", 50);
        map.put("华为", 80);
        map.put("vivo", 30);
        Object[] prices = map.values().toArray();
        Arrays.sort(prices);
        StringBuffer sb = new StringBuffer();
        for(int i=prices.length-1;i>=0;i--){
            int price = Integer.parseInt(prices[i].toString());
            for(Entry<String, Integer> entry : map.entrySet()){
                Integer value = entry.getValue();
                if(value==price){
                    String key = entry.getKey();
                    sb.append("{"+key+", 价格="+value+"},");
                }
            }
        }
        String p_str = sb.toString();
        System.out.println(p_str.substring(0,p_str.length()-1));
    }
}

运行结果:

img


如有帮助,请采纳!