我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?


当前回答

如果你不想重复,使用Set而不是List。要将List转换为Set,可以使用以下代码:

// list is some List of Strings
Set<String> s = new HashSet<String>(list);

如果确实有必要,可以使用相同的结构将Set转换回List。

其他回答

如果你不想重复,使用Set而不是List。要将List转换为Set,可以使用以下代码:

// list is some List of Strings
Set<String> s = new HashSet<String>(list);

如果确实有必要,可以使用相同的结构将Set转换回List。

这是正确的(如果您关心HashSet的开销的话)。

 public static ArrayList<String> removeDuplicates (ArrayList<String> arrayList){
    if (arrayList.isEmpty()) return null;  //return what makes sense for your app
    Collections.sort(arrayList, String.CASE_INSENSITIVE_ORDER);
    //remove duplicates
    ArrayList <String> arrayList_mod = new ArrayList<>();
    arrayList_mod.add(arrayList.get(0));
    for (int i=1; i<arrayList.size(); i++){
        if (!arrayList.get(i).equals(arrayList.get(i-1))) arrayList_mod.add(arrayList.get(i));
    }
    return arrayList_mod;
}

在Java 8中:

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

请注意,列表成员的hashCode-equals契约应该得到尊重,以便过滤正常工作。

虽然将ArrayList转换为HashSet可以有效地删除重复项,但如果您需要保留插入顺序,我宁愿建议您使用这个变体

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

然后,如果需要返回List引用,可以再次使用转换构造函数。

以下是一个适用于任何对象的解决方案:

public static <T> List<T> clearDuplicates(List<T> messages,Comparator<T> comparator) {
    List<T> results = new ArrayList<T>();
    for (T m1 : messages) {
        boolean found = false;
        for (T m2 : results) {
            if (comparator.compare(m1,m2)==0) {
                found=true;
                break;
            }
        }
        if (!found) {
            results.add(m1);
        }
    }
    return results;
}