SHARE
TWEET

MyComp

DulcetAirman Aug 31st, 2016 (edited) 76 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.Comparator;
  5. import java.util.HashMap;
  6.  
  7. public class SomeClass {
  8.  
  9.   public static void main(final String[] arrg) {
  10.     final int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
  11.     final int[] sorted = Arrays.stream(arr).distinct().boxed()
  12.         .sorted(new MyComp(arr)).mapToInt(i -> i).toArray();
  13.     System.out.println(Arrays.toString(sorted));
  14.   }
  15.  
  16.   static class MyComp implements Comparator<Integer> {
  17.  
  18.     final HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  19.     final int[]                     data;
  20.  
  21.     private boolean                 initialized = false;
  22.     public MyComp(final int[] data) {
  23.       this.data = data;
  24.     }
  25.  
  26.     private void init() {
  27.       if(this.initialized) return;
  28.       this.initialized = true;
  29.  
  30.       for (final int i : this.data) {
  31.         // could use map.computeIfAbsent(key, mappingFunction)
  32.         if (this.map.get(i) == null) {
  33.           this.map.put(i, 1);
  34.         } else {
  35.           int count = this.map.get(i);
  36.           this.map.put(i, ++count);
  37.         }
  38.       }
  39.  
  40.     }
  41.  
  42.     @Override
  43.     public int compare(final Integer o1, final Integer o2) {
  44.       this.init();
  45.       final int count1 = this.map.get(o1);
  46.       final int count2 = this.map.get(o2);
  47.       return Integer.compare(count2, count1);
  48.     }
  49.   }
  50. }
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