0

I am getting null when I am trying to get keys to match with sorted values.

public class Linked_L {
static Map<String, Integer> map = new HashMap<>();

public static void sortbyValue(){
        ArrayList<Integer> sortedValues = new ArrayList<>(map.values());
        Collections.sort(sortedValues);
        for (Integer y: sortedValues)
            System.out.println("Key = " +map.get(y) + ", Value = " + y);
    }

public static void main(String args[])
{
    // putting values in the Map
    map.put("Jayant", 80);
    map.put("Abhishek", 90);
    map.put("Anushka", 80);
    map.put("Amit", 75);
    map.put("Danish", 40);

    // Calling the function to sortbyKey
    sortbyValue();
}

Result:

Key = null, Value = 40
Key = null, Value = 75
Key = null, Value = 80
Key = null, Value = 80
Key = null, Value = 90
1
  • map.get requires a key and not a value Commented Mar 10, 2021 at 4:06

2 Answers 2

3

Here:

map.get(y)

y is one of the map's values, but remember what get does? It takes a key of the map, and gives you the value associated with that key, not the other around!

You should sort the map entries (i.e. key value pairs) by their value, rather than taking all the values out, and ignoring all the keys. That way you can get the key of each pair easily in the loop.

ArrayList<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(map.entrySet());
Collections.sort(sortedEntries, Comparator.comparing(Map.Entry::getValue));
for (var entry: sortedEntries) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Sign up to request clarification or add additional context in comments.

Comments

-1

your map stored strings as its key. you get values by integers from it, it of cause returns null~

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.