Dominik Zinser
Dominik Zinser

Reputation: 134

How to sort and print hashMap in java

i got a hashMap in java with the following output when i use the toString()

{to=3, but=2, said=1, hid=1, Newton=6, by=1, eyes=2, of=2, meter=3, hide=1, his=1, on=1, drew=1, Einstein=5,......}

my hashMap has the following syntax: <String, Integer>

now i want to sort it like that :

  6: Newton
  6: and
  5: Einstein
  3: Pascal
  3: found
  3: meter
  3: one
  3: to
  2: a , ....

which means i have to sort by the integer value. also the "style" of the output should be like seen above. can anyone help me please, i have exams tomorrow :D

Upvotes: 1

Views: 3753

Answers (4)

user3781876
user3781876

Reputation: 55

we can not implement sorting on either KEY OR VALUES in HashMap.

java only provide to sort the value using it's key. in java we can sort the key of MAP by using the TreeMap.

TreeMap only provide the facility to sort the keys..

Upvotes: 0

Stephen C
Stephen C

Reputation: 719689

In general, the way to "sort a HashMap" is to copy the keys, values or entries collection into an array, and then sort the array; e.g. using one of the Arrays.sort methods

In your case, you want to extract the collection provided by the HashMap.entrySet() method, using a Comparator that orders the Map<K,V>.Entry objects by value and then by key.

The simple way to print the sorted entries is to use a loop. (I don't think that Arrays.toString is applicable, because Map implementations generally don't override the Object.toString method. At least, the javadoc doesn't say so ...)

Upvotes: 1

santhosh
santhosh

Reputation: 484

Just Implement this with your Prepared map Simple..!!!

Set<Entry<String,Integer>> s=yourmap.entrySet();
    List<Entry<String,Integer>> l=new ArrayList<Entry<String,Integer>>(s);
    Collections.sort(l,new Comparator<Map.Entry<String, Integer>>() {

        @Override
        public int compare(Entry<String, Integer> arg0,
                Entry<String, Integer> arg1) {

            return (arg1.getValue().compareTo(arg0.getValue()));
        }

    });


    for(Map.Entry<String, Integer> entry:l){
        System.out.println("Key== "+entry.getKey()+" value= in Increasing Order=="+entry.getValue());
    }

I Hope this fulfills your requirement

Upvotes: 0

Eran
Eran

Reputation: 394156

It looks like you want to sort the map by its value. I don't think there's any map implementation that does that. TreeMap maintains the keys sorted, but that won't help you.

Therefore, you'll have to write your own method that gets the map's entries (with entrySet()), sorts them by the values (and by the keys for identical values), and prints them however you like.

Upvotes: 3

Related Questions