java - Sorting problem using TreeMap -
i'm trying put key values in hashmap , trying sort out using treemap below. problem if there similar values in map, after sorting considering 1 of them.
import java.util.*; public class hashmapexample { public static void main(string[] args) { hashmap<string,integer> map = new hashmap<string,integer>(); valuecomparator bvc = new valuecomparator(map); treemap<string,integer> sorted_map = new treemap(bvc); map.put("a",99); map.put("b",67); map.put("c",123); map.put("g",67); map.put("f",67); map.put("h",67); map.put("d",6); system.out.println("unsorted map"); (string key : map.keyset()) { system.out.println("key/value: " + key + "/"+map.get(key)); } sorted_map.putall(map); system.out.println("results after sorting"); (string key : sorted_map.keyset()) { system.out.println("key/value: " + key + "/"+sorted_map.get(key)); } } } class valuecomparator implements comparator { map base; public valuecomparator(map base) { this.base = base; } public int compare(object a,object b) { if((integer)base.get(a) > (integer)base.get(b)) { return 1; } else if((integer)base.get(a) == (integer)base.get(b)) { return 0; } else { return -1; } } }
after output below
unsorted map key/value: d/6 key/value: a/99 key/value: f/67 key/value: h/67 key/value: c/123 key/value: b/67 key/value: g/67 results after sorting key/value: d/6 key/value: f/67 key/value: a/99 key/value: c/123
for b,g,f , h keys gave value 67. after sorting map, displaying f value , eleminating b,g , h values. want display outputsomething below
key/value: d/6 key/value: b/67 key/value: g/67 key/value: f/67 key/value: h/67 key/value: a/99 key/value: c/123
the reason keys b,g , h being eliminated because comparator provided compares based on values. since have same values, equal keys, means 1 overwrite others.
to print out want, comparator need first compare values, , if equal, compare keys.
int compare(comparable key1, comparable key2) { // i'm guessing doing like: // return map.get(key1).compareto(map.get(key2)); // can change int result = key1.compareto(key2); if ( result == 0 ) { result= key1.compareto(key2) } return result; }
Comments
Post a Comment