Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (9.5k points)

Below is the HashMap I have which I need to sort according to the values stored in it. I want the keys to get sorted automatically when I sort the values: 

HashMap<Integer,String> map = new HashMap<Integer,String>();

map.put(1,"froyo");

map.put(2,"abby");

map.put(3,"denver");

map.put(4,"frost");

map.put(5,"daisy");

This is my required output:

2,abby;

5,daisy;

3,denver;

4,frost;

1,froyo;

Can anyone tell me how to do it?

 

1 Answer

0 votes
by (19.7k points)

You can implement HashMap in Java like below:

public LinkedHashMap<Integer, String> sortHashMapByValues(

        HashMap<Integer, String> passedMap) {

    List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());

    List<String> mapValues = new ArrayList<>(passedMap.values());

    Collections.sort(mapValues);

    Collections.sort(mapKeys);

    LinkedHashMap<Integer, String> sortedMap =

        new LinkedHashMap<>();

    Iterator<String> valueIt = mapValues.iterator();

    while (valueIt.hasNext()) {

        String val = valueIt.next();

        Iterator<Integer> keyIt = mapKeys.iterator();

        while (keyIt.hasNext()) {

            Integer key = keyIt.next();

            String comp1 = passedMap.get(key);

            String comp2 = val;

            if (comp1.equals(comp2)) {

                keyIt.remove();

                sortedMap.put(key, val);

                break;

            }

        }

    }

    return sortedMap;

}

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 15, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 27, 2021 in Python by laddulakshana (12.7k points)

Browse Categories

...