Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.fhnw.claudemartin;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.HashMap;
- public class SomeClass {
- public static void main(final String[] arrg) {
- final int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
- final int[] sorted = Arrays.stream(arr).distinct().boxed()
- .sorted(new MyComp(arr)).mapToInt(i -> i).toArray();
- System.out.println(Arrays.toString(sorted));
- }
- static class MyComp implements Comparator<Integer> {
- final HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- final int[] data;
- private boolean initialized = false;
- public MyComp(final int[] data) {
- this.data = data;
- }
- private void init() {
- if(this.initialized) return;
- this.initialized = true;
- for (final int i : this.data) {
- // could use map.computeIfAbsent(key, mappingFunction)
- if (this.map.get(i) == null) {
- this.map.put(i, 1);
- } else {
- int count = this.map.get(i);
- this.map.put(i, ++count);
- }
- }
- }
- @Override
- public int compare(final Integer o1, final Integer o2) {
- this.init();
- final int count1 = this.map.get(o1);
- final int count2 = this.map.get(o2);
- return Integer.compare(count2, count1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement