[英]How to remove duplicates from two different lists?
I have two lists in java where I need to remove duplicates. 我在Java中有两个列表需要删除重复项。 One list contains a class (UrlInfo) with three fields, the other contains a list of strings.
一个列表包含具有三个字段的类(UrlInfo),另一个列表包含字符串列表。 I need to compare the list of strings with a field from the class and remove duplicates from the list containing the class.
我需要将字符串列表与类中的字段进行比较,并从包含该类的列表中删除重复项。
Here is what I have right now. 这就是我现在所拥有的。
String urlString;
for (UrlInfo url : urlClass) {
urlString = url.getUrl();
for (int i = 0; i < storedUrlList.size(); i++) {
if (urlString.equals(storedUrlList.get(i))) {
urlClass.remove(url);
}
}
}
This is extremely slow for me. 对我来说这太慢了。 The lists that I will be working with will contain upwards of 100,000 elements.
我将使用的列表将包含多达100,000个元素。
I'd first iterate the List checking if they match the List, if so, I'd store them in a List and then call removeAll() like this: 我首先要遍历List,检查它们是否与List匹配,如果是,我会将它们存储在List中,然后像下面这样调用removeAll():
List<String> toBeComparedWith ...
List<UrlInfo> toBeRemoved = new ArrayList<>();
for (UrlInfo uInfo : urlClass){
if (toBeComparedWith.contains(uInfo.getUrl()){
toBeRemoved.add(uInfo);
}
}
urlClass.removeAll(toBeRemoved);
Because the list to be compared storedUrlList
is a list of strings, so you can use the method List#contains(Object)
to achieve the comparison, and remove the elements from your original list urlClasses
. 因为要比较的列表
storedUrlList
是字符串列表,所以可以使用List#contains(Object)
方法实现比较,并从原始列表urlClasses
删除元素。
In Java 7: 在Java 7中:
ListIterator<UrlClass> iterator = urlClasses.listIterator();
while (iterator.hasNext()) {
UrlClass u = iterator.next();
if (storedUrlList.contains(u.getUrl())) {
iterator.remove();
}
}
In Java 8: 在Java 8中:
urlClasses.removeIf(u -> storedUrlList.contains(u.getUrl()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.