How do I remove repeated elements from ArrayList?

后端 未结 30 1611
难免孤独
难免孤独 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:34

    Suppose we have a list of String like:

    List strList = new ArrayList<>(5);
    // insert up to five items to list.        
    

    Then we can remove duplicate elements in multiple ways.

    Prior to Java 8

    List deDupStringList = new ArrayList<>(new HashSet<>(strList));
    

    Note: If we want to maintain the insertion order then we need to use LinkedHashSet in place of HashSet

    Using Guava

    List deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));
    

    Using Java 8

    List deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());
    

    Note: In case we want to collect the result in a specific list implementation e.g. LinkedList then we can modify the above example as:

    List deDupStringList3 = strList.stream().distinct()
                     .collect(Collectors.toCollection(LinkedList::new));
    

    We can use parallelStream also in the above code but it may not give expected performace benefits. Check this question for more.

提交回复
热议问题