how to remove arraylist duplicate values

前端 未结 5 556
萌比男神i
萌比男神i 2021-01-14 11:45

I am performing some maintenance tasks on an old system. I have an arraylist that contains following values:

a,b,12
c,d,3
b,a,12
d,e,3
a,b,12
5条回答
  •  半阙折子戏
    2021-01-14 12:15

    Wrap the element as "Foo" instead of "String", rest of code 'removeDuplicate' remains:

    public class Foo {
        private String s1;
        private String s2;
        private String s3;
    
        public Foo(String s1, String s2, String s3) {
         this.s1 = s1;
         this.s2 = s2;
         this.s3 = s3;
        }
    
     @Override
        public int hashCode() {
         final int prime = 31;
         int result = 1;
         result = prime * result + ((s1 == null) ? 0 : s1.hashCode());
         result = prime * result + ((s2 == null) ? 0 : s2.hashCode());
         result = prime * result + ((s3 == null) ? 0 : s3.hashCode());
         return result;
        }
    
     @Override
        public boolean equals(Object obj) {
         if (this == obj)
          return true;
         if (obj == null)
          return false;
         if (getClass() != obj.getClass())
          return false;
         Foo other = (Foo) obj;
         //Notice here: 'a,b,12' and 'b,a,12' will be same
         if(fieldsAsList().containsAll(other.fieldsAsList())){
          return true;
         }
    
         return false;
        }
    
     private List fieldsAsList(){
      ArrayList l = new ArrayList(3);
      l.add(s1);
         l.add(s2);
         l.add(s3);
         return l;
     }    
    }
    

    Then arList will be ArrayList < Foo>.

提交回复
热议问题