Sort a map by value

Description:

Sort a map by value

Code:

package com.techonol.algos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class SortByValue {

	public static void main(String a[]) {
		Map<String, Integer> map = new HashMap<String, Integer>();

		map.put("Prajwal", 27);
		map.put("Is", 33);
		map.put("Techonol", 55);
		map.put("Shetty", 7);
		map.put("Author", 45);

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

		for (Map.Entry<String, Integer> entry : list) {
			System.out.println(entry.getKey() + " --> " + entry.getValue());
		}
	}
}

Output:

Techonol --> 55
Author --> 45
Is --> 33
Prajwal --> 27
Shetty --> 7

<< Previous Program | Next Program >>

error: Content is protected !!