How to print and sort the EXACT way by using hash maps Pleas
How to print and sort the EXACT way by using hash maps?
Please enter the name of the input file, or q to suit, · albums.txt U2: 6 Beatles: 5 Madonna: 4 Bob Dylan: 4 Nirvana s 3 Radiohead: 3 Led Zeppelin: 3 Pink Floyd: 3 Rolling Stones: 3 Weezer: 3 Pearl Jam: 3 Bruce Springsteen: 3 Who: 3 Guns N\' Roses: 2 Michael Jackson: 2 Smashing Pumpkins: 2 Eminem: 2 Oasis: Red Hot Chili Peppers: 2 Metallica: 2 Jimi Hendrix: 2 Dave Matthews Band: 2 Clash t 1 Beach Boys: 1 R.E.M.: 1 Tool: 1 Green Day: 1 Jeff Buckley: 1 Fleetwood Mac: 1Solution
Once a map is created from the file use below code:
Set<Entry<String, Integer>> set = hm.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> m1,Map.Entry<String, Integer> m2) {
return m2.getValue().compareTo(m1.getValue());
}
});
for (Entry<String, Integer> entry : list) {
System.out.println(entry.getKey()+\" : \"+entry.getValue());
}
