Java 数组 ArrayList 常用操作:并集、交集、差集、去重、反转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | package wen.jianbao.helper; import java.util.*; /** * ArrayList 助手类 */ public class ArrayListHelper { /** * 并集 */ @SafeVarargs public static <T> ArrayList<T> merge( final ArrayList<T>... lists) { if (lists.length == 0 ) { return null ; } ArrayList<T> mergeList = new ArrayList<>(); for (ArrayList<T> list : lists) { mergeList.addAll(list); } return mergeList; } /** * 交集 * 相同的元素 */ @SafeVarargs public static <T> ArrayList<T> intersect( final ArrayList<T>... lists) { if (lists.length == 0 ) { return null ; } ArrayList<T> intersectList = new ArrayList<>(); // 生成一组以数组元素为key,相同元素的个数为value的中间键值对 HashMap<T, Integer> hashMap = new HashMap<>(); for (ArrayList<T> list : lists) { for (T item : list) { if (hashMap.containsKey(item)) { hashMap.put(item, hashMap.get(item) + 1 ); } else { hashMap.put(item, 1 ); } } } // 统计出相同元素个数正好是数组(参数)个数的元素,即每个数组中都有的元素 for (Map.Entry<T, Integer> entry : hashMap.entrySet()) { if (entry.getValue() == lists.length) { intersectList.add(entry.getKey()); } } return intersectList; } /** * 差集 * 属于 list1 而不属于 list2, list3, list4... */ @SafeVarargs public static <T> ArrayList<T> diff( final ArrayList<T>... lists) { if (lists.length == 0 ) { return null ; } ArrayList<T> diffList = new ArrayList<>(); // 生成一组以数组元素为key,相同元素的个数为value的中间键值对 HashMap<T, Integer> hashMap = new HashMap<>(); for ( int i = 0 ; i < lists.length; i++) { if (i == 0 ) { for (T item : lists[i]) { hashMap.put(item, 1 ); } } else { for (T item : lists[i]) { if (hashMap.containsKey(item)) { hashMap.put(item, hashMap.get(item) + 1 ); } } } } // 统计出相同元素个数为1的元素,即只在第一个数组中出现的元素 for (Map.Entry<T, Integer> entry : hashMap.entrySet()) { if (entry.getValue() == 1 ) { diffList.add(entry.getKey()); } } return diffList; } /** * 去重 * 无重复并集 */ public static <T> ArrayList<T> unique( final ArrayList<T> list) { if (list == null ) { return null ; } Set<T> hashSet = new HashSet<>(list); return new ArrayList<>(hashSet); } /** * 反转 * 如果允许直接改变原数组,可用Java自带方法 Collections.reverse() */ public static <T> ArrayList<T> reverse( final ArrayList<T> list) { if (list == null ) { return null ; } ArrayList<T> reverseList = new ArrayList<>(); for ( int i = list.size() - 1 ; i >= 0 ; i--) { reverseList.add(list.get(i)); } return reverseList; } } |