2017年4月25日 星期二

CompareCollectionUtil

使用CompareCollectionUtil有個大前提

Collection內的Class必須實作 hashCode 和 equal
因為原理是使用equal這個方法在比較

  1. public class CompareCollectionUtil {
  2. /**
  3. * a = [1, 2, 3] b = [2, 3, 4]
  4.  
  5. * 比對兩個List 用 a 去跟 b 比較,回傳缺少的部分
  6.  
  7. * return [1]
  8. **/
  9. public static <T> List<T> deleted(Collection<T> a, Collection<T> b) {
  10. if(a == null){
  11. return new ArrayList<T>();
  12. }
  13.  
  14. List<T> result = new ArrayList<T>(a);
  15.  
  16. if(b != null){
  17. result.removeAll(b);
  18. }
  19.  
  20. return result;
  21. }
  22.  
  23. /**
  24. * a = [1, 2, 3] b = [2, 3, 4]
  25.  
  26. * 比對兩個List 用 a 去跟 b 比較,回傳相同的部分
  27.  
  28. * return [2, 3]
  29. **/
  30. public static <T> List<T> retained(Collection<T> a, Collection<T> b) {
  31. if(a == null || b == null){
  32. return new ArrayList<T>();
  33. }
  34.  
  35. List<T> result = new ArrayList<T>(a);
  36. result.retainAll(b);
  37.  
  38. return result;
  39. }
  40.  
  41. /**
  42. * a = [1, 2, 3] b = [2, 3, 4]
  43.  
  44. * 比對兩個List 用 a 去跟 b 比較,回傳多的部分
  45.  
  46. * return [4]
  47. **/
  48. public static <T> List<T> added(Collection<T> a, Collection<T> b) {
  49. return deleted(b, a);
  50. }
  51.  
  52. /**
  53. * a = [1, 2, 3] b = [2, 3, 4]
  54.  
  55. * 比對兩個List 用 a 去跟 b 比較,回傳不同的部分
  56.  
  57. * return [1, 4]
  58. **/
  59. public static <T> List<T> different(Collection<T> a, Collection<T> b){
  60. List<T> list = new ArrayList<T>();
  61.  
  62. list.addAll(added(a, b));
  63. list.addAll(deleted(a, b));
  64.  
  65. return list;
  66. }
  67. }

沒有留言:

張貼留言