Removing duplicate elements from a List

后端 未结 8 1598
忘掉有多难
忘掉有多难 2020-12-01 17:17

I have developed an array list.

ArrayList list = new ArrayList();

list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.add(\"         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 17:56

    Just use the normal constructor:

    ArrayList yourList;
    HashSet set = new HashSet(yourList);
    

    And you'll have a new view of the items, with duplicates removed, but you will lose ordering. This is true in every answer posted so far. To keep ordering you should iterate on the existing list and remove an element only if it's a duplicate (which can be done using a set to check if an element was already found).

提交回复
热议问题