作者在 2020-12-18 14:23:40 发布以下内容
private static List<String> getRetain(List<String> ... lists ){ if(lists == null){ return null; } ArrayList<List<String>> arrayList = new ArrayList<>(lists.length); int index=0; int flagSize=0; int minIndex=0; for(List<String> s:lists){ if(index == 0){ flagSize = s.size(); }else{ if(flagSize>=s.size()){ flagSize = s.size(); minIndex = index; } } arrayList.add(s); index ++; } for (int i = 0; i < arrayList.size(); i++) { List<String> list = arrayList.get(i); // 去除空集合 if (list == null || list.size() == 0) { arrayList.remove(list); i-- ; } } if(arrayList.size() == 0){ return null; } List<String> intersection = arrayList.get(minIndex); // 就只有一个非空集合,结果就是他 if(arrayList.size() == 1){ return intersection; } arrayList.remove(minIndex); // 有多个非空集合,直接挨个交集 for (int i = 0; i <= arrayList.size()-1; i++) { intersection.retainAll(arrayList.get(i)); } return intersection; }
public static void main(String[] args) { List<String> l1 = new ArrayList<>(); l1.add("q"); l1.add("d"); l1.add("c"); List<String> l2 = new ArrayList<>(); l2.add("a"); l2.add("c"); l2.add("v"); l2.add("b"); List<String> l3 = new ArrayList<>(); l3.add("a"); l3.add("c"); List<String> l4 = new ArrayList<>(); System.out.println("l3,l1------>"+getRetain(l3,l1)); System.out.println("l1,l3------>"+getRetain(l1,l3)); System.out.println("l1,l2,l3--->"+getRetain(l1,l2,l3)); System.out.println("l2,l3------>"+getRetain(l2,l3)); System.out.println("l3,l2------>"+getRetain(l3,l2)); System.out.println("l4,l1------>"+getRetain(l4,l1)); System.out.println("l1,l4,l3--->"+getRetain(l1,l4,l3)); }
返回结果:
l3,l1------>[c] l1,l3------>[c] l1,l2,l3--->[c] l2,l3------>[c] l3,l2------>[c] l4,l1------>[q, d, c] l1,l4,l3--->[c]