Java8之前做法:
/** * 从 有值的 list 里取交集 * @param lists * @return */ public List<Object> intersection(List<List<Object>> lists) { if(lists == null || lists.size() == 0){ return null; } ArrayList<List<Object>> arrayList = new ArrayList<>(lists); for (int i = 0; i < arrayList.size(); i++) { List<Object> list = arrayList.get(i); // 去除空集合 if (list == null || list.size() == 0) { arrayList.remove(list); i-- ; } } if(arrayList.size() == 0){ return null; } List<Object> intersection = arrayList.get(0) ; // 就只有一个非空集合,结果就是他 if(arrayList.size() == 1){ return intersection; } // 有多个非空集合,直接挨个交集 for (int i = 1; i < arrayList.size()-1; i++) { intersection.retainAll(arrayList.get(i)); } return intersection; }
Stream风格的:
public static List<Element> retainElementList(List<List<Element>> elementLists) { Optional<List<Element>> result = elementLists.parallelStream() .filter(elementList -> elementList != null && ((List) elementList).size() != 0) .reduce((a, b) -> { a.retainAll(b); return a; }); return result.orElse(new ArrayList<>()); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14589.html