0

My code sorts a tree map but it do not print duplicate values it also show one of these duplicate values. Can I change it or no? if no, what can I do instead?

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());
    } 

the output is:

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

and I want to be like this:

0.5: noha
0.5: olaa
0.2: omar
0.13: saeed
0.13: nahla
0.1: sara
Sara Shall
  • 31
  • 1
  • 6
  • Do you just need to flip it so the name is the key? – JustinKSU May 01 '18 at 18:38
  • my code is dynamic I do not know when keys are equal to each other. This code is an example since the original one is complicated a little bit. – Sara Shall May 01 '18 at 18:59
  • I think you could put the name as the key and the value of the number. Then if you want it sorted by the number you can sort the map by the value instead of key by following https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values – JustinKSU May 01 '18 at 21:22

1 Answers1

0

TreeMap doesnt allow duplicates so instead use LinkedMultiValueMap from org.springframework.util.LinkedMultiValueMap to store and the then sort it.

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;

}
}