我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?
当前回答
假设我们有一个字符串列表,像这样:
List<String> strList = new ArrayList<>(5);
// insert up to five items to list.
然后我们可以用多种方式删除重复的元素。
Java 8之前
List<String> deDupStringList = new ArrayList<>(new HashSet<>(strList));
注意:如果我们想保持插入顺序,那么我们需要使用LinkedHashSet来代替HashSet
使用番石榴
List<String> deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));
使用Java 8
List<String> deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());
注意:如果我们想在一个特定的列表实现中收集结果,例如LinkedList,那么我们可以修改上面的例子:
List<String> deDupStringList3 = strList.stream().distinct()
.collect(Collectors.toCollection(LinkedList::new));
我们也可以在上面的代码中使用parallelStream,但它可能不会带来预期的性能优势。查看这个问题了解更多信息。
其他回答
如果您希望列表自动忽略重复项并保持其顺序,则可以创建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 l1 = new ArrayList();
ArrayList l2 = new ArrayList();
Iterator iterator = l1.iterator();
while (iterator.hasNext()) {
YourClass o = (YourClass) iterator.next();
if(!l2.contains(o)) l2.add(o);
}
L1是原始列表,l2是没有重复项的列表 (确保你的类有equals方法,根据你想要代表的相等)
LinkedHashSet可以做到这一点。
String[] arr2 = {"5","1","2","3","3","4","1","2"};
Set<String> set = new LinkedHashSet<String>(Arrays.asList(arr2));
for(String s1 : set)
System.out.println(s1);
System.out.println( "------------------------" );
String[] arr3 = set.toArray(new String[0]);
for(int i = 0; i < arr3.length; i++)
System.out.println(arr3[i].toString());
/ /输出:5、1、2、3、4
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());
如何从数组列表中删除重复的元素
用于自定义对象列表
public List<Contact> removeDuplicates(List<Contact> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (((Contact) o1).getId().equalsIgnoreCase(((Contact) o2).getId()) /*&&
((Contact)o1).getName().equalsIgnoreCase(((Contact)o2).getName())*/) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}