Advertisement
DulcetAirman

sortByFrequency

Aug 31st, 2016
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.fhnw.claudemartin;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collections;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.TreeMap;
  10.  
  11. public class SomeClass {
  12.  
  13.   public static void main(final String[] arrg) {
  14.     final int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
  15.     System.out.println(Arrays.toString(sortByFrequency(arr)));
  16.   }
  17.  
  18.   static final int[] sortByFrequency(final int[] input) {
  19.     final Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
  20.     for (final int i : input) {
  21.       if (map.get(i) == null) {
  22.         map.put(i, 1);
  23.       } else {
  24.         int count = map.get(i);
  25.         map.put(i, ++count);
  26.       }
  27.     }
  28.  
  29.     final List<Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
  30.     list.sort(Collections.reverseOrder(Entry.comparingByValue()));
  31.     return list.stream().mapToInt(e -> e.getKey()).toArray();
  32.  
  33.   }
  34.  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement