Reputation: 23
I have keys values, now I would like sort values only by adding it to the tree-set. Because tree-set performs the ascending order sorting.
There exist a method that converting called converting map to list. But it is a hectic method, can any one comment about this?
package practice;
import java.io.ObjectInputStream.GetField;
import java.util.*;
import java.util.Map.Entry;
public class example1{
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "h");
map.put(2, "l");
map.put(3, "a");
System.out.println(map);
System.out.println("unsort");
for(Map.Entry m:map.entrySet()) {
System.out.println(m.getKey()+" - "+m.getValue());
}
System.out.println("sorting by values");
}
}
Upvotes: 0
Views: 4191
Reputation: 11
String s1 = new String("A");
String s2 = new String("B");
String s3 = new String("C");
String s4 = new String("D");
String s5 = new String("F");
Map<String,String> map1 = new HashMap<>();
map1.put(s1, "AAA");
map1.put(s2, "BBB");
map1.put(s3, "CCC");
map1.put(s4, "FFF");
map1.put(s5, "DDD");
System.out.println(map1);
Set<Map.Entry<String, String>> set = new TreeSet<>(new SortHashValue());
set.addAll(map1.entrySet());
System.out.println(set);
class SortHashValue implements Comparator<Map.Entry<String, String>>{
public int compare(Entry<String, String> e1, Entry<String, String> e2) {
String v1 = e1.getValue();
String v2 = e2.getValue();
return v1.compareTo(v2);
}
}
Upvotes: 1
Reputation: 522
Yes you can do this:
HashMap<String, String> hashmap = new HashMap<>();
hashmap.put("k1", "Zz");
hashmap.put("k2", "A");
hashmap.put("k3", "Zd");
hashmap.put("k4", "Zd");
TreeSet<String> set = new TreeSet<>(hashmap.values());
But be careful, in this example this way of "sorting" wil result in a set containing 3 elements (the 4th "k4" entry in hashmap will get lost)
I would recommend to use java streams
List<String> collect = hashmap.values().stream().sorted().collect(Collectors.toList());
this will sort and keep all values.
Upvotes: 1