我有一个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;
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 为什么元组可以包含可变项?
- 在Jar文件中运行类
- 带参数的可运行?
- 如何检查IEnumerable是否为空或空?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作