How print out the contents of a HashMap in ascending order based on its values?

前端 未结 13 1503
春和景丽
春和景丽 2020-12-24 11:58

I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys

相关标签:
13条回答
  • 2020-12-24 12:43

    the for loop of for(Map.Entry entry: codes.entrySet()) didn't work for me. Used Iterator instead.

    Iterator<Map.Entry<String, String>> i = codes.entrySet().iterator(); 
    while(i.hasNext()){
        String key = i.next().getKey();
        System.out.println(key+", "+codes.get(key));
    }
    
    0 讨论(0)
  • 2020-12-24 12:44
    while (itr.hasNext()) {
        Vehicle vc=(Vehicle) itr.next();
        if(vc.getVehicleType().equalsIgnoreCase(s)) {
            count++;
        }
    }
    
    0 讨论(0)
  • 2020-12-24 12:47
    1. Create a TreeMap<String,String>
    2. Add each of the HashMap entries with the value as the key.
    3. iterate the TreeMap

    If the values are nonunique, you would need a list in the second position.

    0 讨论(0)
  • 2020-12-24 12:53

    It's time to add some lambdas:

    codes.entrySet()
        .stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .forEach(System.out::println);
    
    0 讨论(0)
  • 2020-12-24 12:53

    the simplest and shortest code i think is this:

    public void listPrinter(LinkedHashMap<String, String> caseList) {
    
        for(Entry entry:caseList.entrySet()) {
            System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
        }
    }
    
    0 讨论(0)
  • 2020-12-24 12:55

    Java 8

    map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);
    
    0 讨论(0)
提交回复
热议问题