JAVA: Preventing Duplicate Entries to an ArrayList

前端 未结 6 1710

I am trying to prevent duplicate entries from being added to an ArrayList as the list is being populated whilst reading through each line of a file. Each line of the file is

6条回答
  •  独厮守ぢ
    2021-01-12 00:41

    Use a LinkedHashSet and then convert it to an ArrayList, because a LinkedHashSet has a predictable iteration order (the insertion-order) and it is a Set.

    For example

    LinkedHashSet uniqueStrings = new LinkedHashSet();
    
    uniqueStrings.add("A");
    uniqueStrings.add("B");
    uniqueStrings.add("B");
    uniqueStrings.add("C");
    uniqueStrings.add("A");
    
    List asList = new ArrayList(uniqueStrings);
    System.out.println(asList);
    

    will output

     [A, B, C]
    

提交回复
热议问题