我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?
当前回答
在Java 8中:
List<String> deduped = list.stream().distinct().collect(Collectors.toList());
请注意,列表成员的hashCode-equals契约应该得到尊重,以便过滤正常工作。
其他回答
如果不希望集合中有重复项,则应该考虑为什么要使用允许重复项的集合。删除重复元素最简单的方法是将内容添加到Set(不允许重复),然后将Set添加回ArrayList:
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
当然,这破坏了数组列表中元素的顺序。
如果你不想重复,使用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;
}
如果您希望列表自动忽略重复项并保持其顺序,则可以创建HashList(HashMap嵌入式列表)。
public static class HashList<T> extends ArrayList<T>{
private HashMap <T,T> hashMap;
public HashList(){
hashMap=new HashMap<>();
}
@Override
public boolean add(T t){
if(hashMap.get(t)==null){
hashMap.put(t,t);
return super.add(t);
}else return false;
}
@Override
public boolean addAll(Collection<? extends T> c){
HashList<T> addup=(HashList<T>)c;
for(int i=0;i<addup.size();i++){
add(addup.get(i));
}return true;
}
}
使用的例子:
HashList<String> hashlist=new HashList<>();
hashList.add("hello");
hashList.add("hello");
System.out.println(" HashList: "+hashlist);
ArrayList<String> city=new ArrayList<String>();
city.add("rajkot");
city.add("gondal");
city.add("rajkot");
city.add("gova");
city.add("baroda");
city.add("morbi");
city.add("gova");
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(city);
city.clear();
city.addAll(hashSet);
Toast.makeText(getActivity(),"" + city.toString(),Toast.LENGTH_SHORT).show();