how to remove arraylist duplicate values

前端 未结 5 423
萌比男神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:14

    Assuming the entries are String. Then you can sort each of the entry and then do the duplicate check. Then you can store the entry in a map and use the contains(key) to see if they exist.

    EDIT: added a complete code example.

    public class Test {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Test test = new Test();
            List someList = new ArrayList(); 
            someList.add("d,e,3");
            someList.add("a,b,12");
            someList.add("c,d,3");
            someList.add("b,a,12");
            someList.add("a,b,12");
                //using a TreeMap since you care about the order
            Map dupMap = new TreeMap();
            String key = null;
            for(String some:someList){
                key = test.sort(some);
                if(key!=null && key.trim().length()>0 && !dupMap.containsKey(key)){
                    dupMap.put(key, some);
                }
            }
            List uniqueList = new ArrayList(dupMap.values());
            for(String unique:uniqueList){
                System.out.println(unique);
            }
    
        }
        private String sort(String key) {
          if(key!=null && key.trim().length()>0){
            char[] keys = key.toCharArray();
            Arrays.sort(keys);
            return String.valueOf(keys);
          }
          return null;
       }
    }
    

    Prints:

    a,b,12

    c,d,3

    d,e,3

提交回复
热议问题