Compare two Java Collections using Comparator instead of equals()

后端 未结 4 1245
臣服心动
臣服心动 2021-02-12 21:09

Problem Statement

I have two Collections of the same type of object that I want to compare. In this case, I want to compare them based on an attribute that does not fa

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 21:25

    I'm not sure this way is actually better, but it is "another way"...

    Take your original two collections, and create new ones containing an Adapter for each base object. The Adapter should have .equals() and .hashCode() implemented as being based on Name.calculateWeightedRank(). Then you can use normal Collection equality to compare the collections of Adapters.

    * Edit *

    Using Eclipse's standard hashCode/equals generation for the Adapter. Your code would just call adaptCollection on each of your base collections, then List.equals() the two results.

    public class Adapter {
    
        public List adaptCollection(List names) {
            List adapters = new ArrayList(names.size());
    
            for (Name name : names) {
                adapters.add(new Adapter(name));
            }
    
            return adapters;
        }
    
    
        private final int name;
    
        public Adapter(Name name) {
            this.name = name.getWeightedResult();
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + name;
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Adapter other = (Adapter) obj;
            if (name != other.name)
                return false;
            return true;
        }
    
    }
    

提交回复
热议问题