首页 > 解决方案 > 如何使树状图降序显示重复值

问题描述

我的代码对树形图进行排序,但它不打印重复值,它还显示这些重复值之一。我可以更改或不更改吗?如果没有,我能做些什么呢?

TreeMap<Double,String> hm=new TreeMap<Double,String>(Collections.reverseOrder());

hm.put(0.1,"sara"); 
hm.put(0.13,"nahla");
hm.put(0.13,"saeed");
hm.put(0.2,"omar");
hm.put(0.5,"olaa");
hm.put(0.5,"noha");

Set set = hm.entrySet();
    Iterator i2 = set.iterator();
   while(i2.hasNext()) {
      Map.Entry me = (Map.Entry)i2.next();
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    } 

输出是:

0.5: noha
0.2: omar
0.13: saeed
0.1: sara

我想成为这样:

0.5: noha
0.5: olaa
0.2: omar
0.13: saeed
0.13: nahla
0.1: sara

标签: javasortingnetbeanssearch-enginetreemap

解决方案


TreeMap不允许重复,所以改为使用LinkedMultiValueMapfrom org.springframework.util.LinkedMultiValueMap来存储然后对其进行排序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

public class ds {

public static void main(String[] args) {

    MultiValueMap<Double, String> map = new LinkedMultiValueMap<Double, String>();
    map.add(8.9, "g");
    map.add(4.6, "h");
    map.add(10.5, "a");
    map.add(10.5, "b");
    map.add(9.6, "c");
    map.add(8.6, "d");
    map.add(8.6, "e");
    map.add(8.0, "f");
    map.add(2.8, "i");

    MultiValueMap<Double, String> filteredMap = filter(5, map);
    System.out.println(filteredMap.toString());

}

public static MultiValueMap<Double, String> filter(int numberOfResults,
        MultiValueMap<Double, String> map) {
    MultiValueMap<Double, String> result = new LinkedMultiValueMap<Double, String>();

    List<Double> keys = new ArrayList<Double>(map.keySet());
    Collections.sort(keys, Collections.reverseOrder());

    for (Double key : keys) {
        if (result.size() <= numberOfResults) {
            result.put(key, map.get(key));
        } else {
            break;
        }
    }

    return result;

}
}

推荐阅读