سؤال

I created a map and I want to sort it by the value but I need to give the output as a list of the strings only. I think I can sort the map by extending comparable and then add every sorted key to a list but I'm not sure it is the best way. Any ideas?

//code is not finished yet//
public List<String> search(String prefix) {
    Map <String, Integer> suitable_sites = new LinkedHashMap<>() ;
    List<String> sorted_list = new ArrayList<>();
    for (Map.Entry<String, Site<String>> site :index.entrySet()) {
        Map <String, Integer> words = site.getValue().getWords() ;
        int counter =0 ;
        for (String word : words.keySet()) {
            if (word.startsWith(prefix))
                counter++;
        }
        int weight = counter / site.getValue().getAmmount();
        if (weight == 0 )
            continue;
        suitable_sites.put(site.getKey(), weight);
    }
    return  null;
}
هل كانت مفيدة؟

المحلول

    final HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("abcd",5);
    map.put("xyz",152);
    map.put("pqr",1);
    List list = new ArrayList<String>(map.keySet());

    System.out.println("before : "+ list);
    Collections.sort(list, new Comparator<String>(){
        public int compare(String item1, String item2){
            int compare = map.get(item1) - map.get(item2);
            if(compare == 0)
            {  
                return (item1.compareTo(item2)); 
            }
            return compare;
        }
    });

    System.out.println("after : "+ list);

This code is using inline comparator.. if values are same than we consider lexical order.This will print below

before : [pqr, abcd, xyz]

after : [pqr, abcd, xyz]

نصائح أخرى

Implement your Map Values to Comparable.

And then do the following

// Populate the Map
List<String> mapValues = new ArrayList<String>(map.values());
Collections.sort(mapValues);

If your values are String you dont need to implement Comparable if you are satisfied with Default String Sorting Mechanism

HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(1,"xyz");
        map.put(2,"abcd");
        List<String> mapValues = new ArrayList<String>(map.values());
        Collections.sort(mapValues);
        System.out.println(mapValues);

UPDATE

I initially thought, OP just wanted to sort by Values and return as List. Based on comments, OP wants to sort by Values and return the Keys as List .

public static void main(String args[]) {
        //  readTempFile();
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        map.put("C",2);
        map.put("A",3);
        map.put("B",1);
        System.out.println(sortByValues(map));

    }

    public static <K, V extends Comparable<V>> List<K> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k1).compareTo(map.get(k2));
            if (compare == 0) {
                return 1;
            } else {
                return compare;
            }
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return new ArrayList<K>(sortedByValues.keySet());
}

And the result

 [B, C, A]

Credit Goes tooooo

    final HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("abcd",50);
    map.put("xyz",15);
    map.put("pqr",10);
    List list = new ArrayList<String>(map.keySet());

    System.out.println("before : "+ list);
    Collections.sort(list, new Comparator<String>(){
        public int compare(String item1, String item2){
           return  map.get(item1).compareTo(map.get(item2));
        }
    });

    System.out.println("after : "+ list);
    return list;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top