I have an ArrayList
, and I want to remove repeated strings from it. How can I do this?
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.
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
List deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));
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.