MyCollectionUtils.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package io.jpress.utils;
  2. import java.util.Collection;
  3. import java.util.HashMap;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. /**
  7. * Created by 黄诚天 on 2017-10-13.
  8. */
  9. public class MyCollectionUtils {
  10. private static final Integer INTEGER_ONE = 1;
  11. public static boolean isEqualCollection(Collection a, Collection b) {
  12. if (a == null && b == null) {
  13. return true;
  14. } else if (a == null && b != null) {
  15. return false;
  16. } else if (a != null && b == null) {
  17. return false;
  18. }
  19. if (a.size() != b.size()) { // size是最简单的相等条件
  20. return false;
  21. }
  22. Map mapa = getCardinalityMap(a);
  23. Map mapb = getCardinalityMap(b);
  24. // 转换map后,能去掉重复的,这时候size就是非重复项,也是先决条件
  25. if (mapa.size() != mapb.size()) {
  26. return false;
  27. }
  28. Iterator it = mapa.keySet().iterator();
  29. while (it.hasNext()) {
  30. Object obj = it.next();
  31. // 查询同一个obj,首先两边都要有,而且还要校验重复个数,就是map.value
  32. if (getFreq(obj, mapa) != getFreq(obj, mapb)) {
  33. return false;
  34. }
  35. }
  36. return true;
  37. }
  38. /**
  39. * 以obj为key,可以防止重复,如果重复就value++
  40. * 这样实际上记录了元素以及出现的次数
  41. */
  42. public static Map getCardinalityMap(Collection coll) {
  43. Map count = new HashMap();
  44. for (Iterator it = coll.iterator(); it.hasNext(); ) {
  45. Object obj = it.next();
  46. Integer c = (Integer) count.get(obj);
  47. if (c == null)
  48. count.put(obj, INTEGER_ONE);
  49. else {
  50. count.put(obj, new Integer(c.intValue() + 1));
  51. }
  52. }
  53. return count;
  54. }
  55. private static final int getFreq(Object obj, Map freqMap) {
  56. Integer count = (Integer) freqMap.get(obj);
  57. if (count != null) {
  58. return count.intValue();
  59. }
  60. return 0;
  61. }
  62. }