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


当前回答

这是正确的(如果您关心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;
}

其他回答

还有来自Guava的ImmutableSet作为一个选项(这里是文档):

ImmutableSet.copyOf(list);

如果不希望集合中有重复项,则应该考虑为什么要使用允许重复项的集合。删除重复元素最简单的方法是将内容添加到Set(不允许重复),然后将Set添加回ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

当然,这破坏了数组列表中元素的顺序。

科特林

val list = listOf('a', 'A', 'b', 'B', 'A', 'a')
println(list.distinct()) // [a, A, b, B]
println(list.distinctBy { it.uppercaseChar() }) // [a, b]

从这里kotlinlang

Java 8流提供了一种从列表中删除重复元素的非常简单的方法。使用不同的方法。 如果我们有一个城市列表,我们想要从该列表中删除重复的城市,可以在一行中完成-

 List<String> cityList = new ArrayList<>();
 cityList.add("Delhi");
 cityList.add("Mumbai");
 cityList.add("Bangalore");
 cityList.add("Chennai");
 cityList.add("Kolkata");
 cityList.add("Mumbai");

 cityList = cityList.stream().distinct().collect(Collectors.toList());

如何从数组列表中删除重复的元素

for(int a=0;a<myArray.size();a++){
        for(int b=a+1;b<myArray.size();b++){
            if(myArray.get(a).equalsIgnoreCase(myArray.get(b))){
                myArray.remove(b); 
                dups++;
                b--;
            }
        }
}