SHARE
TWEET

sortByFrequency

DulcetAirman Aug 31st, 2016 (edited) 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.fhnw.claudemartin;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import java.util.stream.Collectors;
  8.  
  9. public class SomeClass {
  10.  
  11.   public static void main(final String[] arrg) {
  12.     final int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
  13.     System.out.println(Arrays.toString(sortByFrequency(arr)));
  14.   }
  15.  
  16.   static final int[] sortByFrequency(final int[] input) {
  17.     final List<Integer> list = Arrays.stream(input).boxed().collect(Collectors.toList());
  18.     final Comparator<Integer> comp = (a,b) -> Integer.compare(Collections.frequency(list, b), Collections.frequency(list, a));
  19.     return Arrays.stream(input).distinct().boxed().sorted(comp).mapToInt(i -> i).toArray();
  20.   }
  21.  
  22. }
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