简体   繁体   中英

Please how do I sort map elements based on values in ascending order in java?

I am trying to sort map elements (based on values) by using Collections.sort(). The problem is that my program sorts the elements in descending order instead of sorting it in ascending order. How can I sort it in ascending order? Below is my code.

package hashTableRR;

import java.util.*;
import java.util.Map.Entry;
public class OrderByValue {

    public static void main(String [] args){

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(1, 4);
    map.put(2, 6);
    map.put(3, 1);
    map.put(4, 1);
    map.put(6, 8);
    map.put(7, 5);

    Set<Entry<Integer, Integer>> set = map.entrySet();
    List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
    {
        public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){
            return(o2.getValue()).compareTo(o1.getValue());
        }
    }

            );

    System.out.println("Keys\t\tValues");
    for(Map.Entry<Integer, Integer> entry:list)
    {
        System.out.println(" "+entry.getKey()+"\t\t  "+entry.getValue());

    }       


    }
}

只需在您的compare函数中更改变量的顺序

return(o1.getValue()).compareTo(o2.getValue());

The problem is likely in your Comparator#compare implementation.

You are returning: o2.getValue().compareTo(o1.getValue())

For an ascending order, you should return: o1.getValue().compareTo(o2.getValue())

This will generate a negative value if o1 < o2 , 0 if they're equal and a positive value if o2 > o1 .

See slightly cryptical documentation here .


Here's an insight of what values you can expect your Comparator to return when performing a comparison of Integer s in Java (full doc here ):

the value 0 if this Integer is equal to the argument Integer; a value less than 0 if this Integer is numerically less than the argument Integer; and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison).

Just use :

return(o1.getValue()).compareTo(o2.getValue());

It will obviously inverse order

 Map<Integer, Integer> unsortedMap = new HashMap<>();
    Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
    unsortedMap.put(1, 4);
    unsortedMap.put(2, 6);
    unsortedMap.put(3, 1);
    unsortedMap.put(4, 1);
    unsortedMap.put(6, 8);
    unsortedMap.put(7, 5);


    unsortedMap.entrySet().
            stream().
            sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()).
            forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

    System.out.println(sortedMap);

Use LinkedHashMap if you want to store your data in the order in which keys are inserted into the Map . HashMap doesn't guarantee any order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM