Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapCountSorter<E, U> implements Comparator<E> {
  8.  
  9. public static enum Sort {
  10. ASC, DESC
  11. }
  12.  
  13. private final Map<E, List<U>> map;
  14. private final Sort sort;
  15.  
  16. private MapCountSorter(Map<E, List<U>> map, Sort direction) {
  17. this.map = map;
  18. this.sort = direction;
  19. }
  20.  
  21. public static <T, U> List<T> getOrder(Map<T, List<U>> map, Sort sort) {
  22. List<T> order = new ArrayList<T>(map.keySet());
  23. Collections.sort(order, new MapCountSorter<T, U>(map, sort));
  24. return order;
  25. }
  26.  
  27. @Override
  28. public int compare(E obj0, E obj1) {
  29. if (map.containsKey(obj0) && map.containsKey(obj1)) {
  30. List<? extends Object> list0 = map.get(obj0);
  31. List<? extends Object> list1 = map.get(obj1);
  32. if (list0 != null && list1 != null) {
  33. if (sort == Sort.ASC) {
  34. return list0.size() - list1.size();
  35. } else {
  36. return list1.size() - list0.size();
  37. }
  38. } else {
  39. return 0;
  40. }
  41. } else {
  42. return 0;
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement