如何使树图降序排序显示重复值

时间:2018-05-01 18:24:51

标签: java sorting netbeans search-engine treemap

我的代码对树图进行排序,但它不会打印重复值,它也会显示其中一个重复值。我可以改变它吗?如果不是,我该怎么办呢?

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

1 个答案:

答案 0 :(得分:0)

TreeMap不允许重复,因此请使用LinkedMultiValueMap 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;

}
}