Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()

前端 未结 8 1133
庸人自扰
庸人自扰 2020-11-27 03:50

I have an array of objects and I want to concatenate it with another array of objects, except that objects that have same id\'s. That objects are used in many places in the

8条回答
  •  -上瘾入骨i
    2020-11-27 04:14

    Just had this problem and worked up a simple solution. Not sure how memory-intensive it is; I'm sure people can refine it down the line.

    When the Comparator returns 0, the elements match.

    public static  Set filterSet(Set set, Comparator comparator){
        Set output = new HashSet();
        for(E eIn : set){
            boolean add = true;
            for(E eOut : output){
                if(comparator.compare(eIn, eOut) == 0){
                    add = false;
                    break;
                }
            }
            if(add) output.add(eIn);
        }
        return output;
    }
    

    My use case was that I needed to filter out duplicate URLs, as in URLs that point to the same document. The URL object has a samePage() method that will return true if everything except the fragment are the same.

    filtered = Misc.filterSet(filtered, (a, b) -> a.sameFile(b) ? 0 : 1);
    

提交回复
热议问题