Intersection and union of ArrayLists in Java

后端 未结 24 2221
离开以前
离开以前 2020-11-22 06:05

Are there any methods to do so? I was looking but couldn\'t find any.

Another question: I need these methods so I can filter files. Some are AND filter

24条回答
  •  鱼传尺愫
    2020-11-22 07:01

    If the objects in the list are hashable (i.e. have a decent hashCode and equals function), the fastest approach between tables approx. size > 20 is to construct a HashSet for the larger of the two lists.

    public static  ArrayList intersection(Collection a, Collection b) {
        if (b.size() > a.size()) {
            return intersection(b, a);
        } else {
            if (b.size() > 20 && !(a instanceof HashSet)) {
                a = new HashSet(a);
            }
            ArrayList result = new ArrayList();
            for (T objb : b) {
                if (a.contains(objb)) {
                    result.add(objb);
                }
            }
            return result;
        }
    }
    

提交回复
热议问题