How do I remove repeated elements from ArrayList?

后端 未结 30 1614
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 06:49

    It is possible to remove duplicates from arraylist without using HashSet or one more arraylist.

    Try this code..

        ArrayList lst = new ArrayList();
        lst.add("ABC");
        lst.add("ABC");
        lst.add("ABCD");
        lst.add("ABCD");
        lst.add("ABCE");
    
        System.out.println("Duplicates List "+lst);
    
        Object[] st = lst.toArray();
          for (Object s : st) {
            if (lst.indexOf(s) != lst.lastIndexOf(s)) {
                lst.remove(lst.lastIndexOf(s));
             }
          }
    
        System.out.println("Distinct List "+lst);
    

    Output is

    Duplicates List [ABC, ABC, ABCD, ABCD, ABCE]
    Distinct List [ABC, ABCD, ABCE]
    

提交回复
热议问题