0

I'm struggling o the following task: I'm adding Characters and Integers (the int is the number of apperances of a certain character) to a LinkedHashMap (yes, unfortunatly I have to use this).

How can i print it out orderer?

 LinkedHashMap<Character, Integer> map = new LinkedHashMap();
 int a=7;
 int b=6;
 int c=9;
 map.put('a', a);
 map.put('b', b);
 map.put('c', c);

Output should look like this:

 c 9
 a 7
 b 6
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
Stunt
  • 1
  • 2
    can you explain what you have tried? There are tons of duplicate http://stackoverflow.com/questions/12184378/sorting-linkedhashmap – sidgate Jan 08 '15 at 09:32
  • Can you store primitive data types in Maps, I believe you can store only objects. you have wrapper classes to do that. – saikumarm Jan 08 '15 at 09:34
  • 1
    @saikumar - Read about *AutoBoxing*. – TheLostMind Jan 08 '15 at 09:36
  • Because c has the highest value and b the lowest – Stunt Jan 08 '15 at 09:36
  • And I've seen the duplicates, but I don't want to sort it into another List I just want to print it out in the format Key(blankspace) value in a ordered way – Stunt Jan 08 '15 at 09:37
  • @Stunt - You can't sort *hash based structures*. You will have to either change your data structure to `TreeMap`which accepts a `Comparator` or get the entry set, parse key value and then print. – TheLostMind Jan 08 '15 at 09:41
  • @TheLostMind Could you write me down how the parsing of key and values for entry sets is done? – Stunt Jan 08 '15 at 09:43

4 Answers4

0

You could convert the map to a TreeMap which can be sorted. The default map is sorted by the natural ordering of the keys, which should be sufficient for you as you use Integer...

TreeMap tm = new TreeMap( map );
jo-
  • 234
  • 1
  • 9
  • This will sort only in *Natural Order*. Which is not what the OP wants – TheLostMind Jan 08 '15 at 09:48
  • There is also a constructor for TreeMap which takes a comparator: TreeMap(Comparator super K> comparator). Implementing a comparator that sorts Integers descending instead of ascending should be easy enough. – jo- Jan 08 '15 at 09:58
0

How try like this,

The method to sort Map based on Value DESC

public static Map<Character, Integer> mapSortedByValues(Map<Character, Integer> map) {
    List<Map.Entry<Character, Integer>> entryList = new LinkedList<Map.Entry<Character, Integer>>(map.entrySet());
    Collections.sort(entryList,
            new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> e1, Map.Entry<Character, Integer> e2) {
                    return (e1.getValue()).compareTo(e2.getValue());
                }
            }
    );
    Collections.reverse(entryList); //Reverse value DESC
    Map<Character, Integer> sortedMap = new LinkedHashMap<Character, Integer>();
    for (Map.Entry<Character, Integer> entry : entryList)
        sortedMap.put(entry.getKey(), entry.getValue());
    return sortedMap;
}

Testing value sorting;

public static void main(String[] args) {
    LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
    map.put('a', 7);
    map.put('b', 9);
    map.put('c', 6);

    Map sortedMap = mapSortedByValues(map);
    System.out.println(sortedMap);
}

Will output

{c=9, a=7, b=6}
Wundwin Born
  • 3,467
  • 19
  • 37
0
  1. Put the map in a list.
  2. Sort the list.
  3. Put the list back to map.
  4. Resign the sorted map to your map.

Here's the code

 List list =new LinkedList<Map.Entry<String, Integer>>( map.entrySet() );

 Collections.sort(list, (Map.Entry o1, Map.Entry o2) ->{
                       return (o2.getValue()).compareTo(o1.getValue())
                 });

 Map result = new LinkedHashMap<String, Integer>();
 for (Map.Entry entry : list){
    result.put( entry.getKey(), entry.getValue() );
 }

 map = result
Sorter
  • 9,704
  • 6
  • 64
  • 74
0
map.entrySet().stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));

This reverses the normal compareTo to make the order reverse. If you can use the natural ordering then it's a bit simpler:

.sorted(Map.Entry::comparingByValue)
sprinter
  • 27,148
  • 6
  • 47
  • 78