SHARE
TWEET

sortByFrequency

DulcetAirman Aug 31st, 2016 (edited) 67 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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top