[英]Remove specific duplicates in ArrayList in Java
How can I remove duplicates in an ArrayList in Java, except for specific elements? 除了特定元素,如何删除Java中ArrayList中的重复项? For instance if I have an ArrayList with
例如,如果我有一个ArrayList
"a", "b", "c", "d", "d", "a", "b", "b", "d", "c"
I only want to remove the duplicates for "a"
, "b"
and "c"
and I also need to maintain the order of the elements. 我只想删除
"a"
, "b"
和"c"
的重复项,并且还需要保持元素的顺序。 The duplicates of "d"
cannot be removed. 无法删除
"d"
的重复项。
How can I accomplish this? 我该怎么做?
You will have to maintain 2 lists: 您将必须维护2个列表:
One which is the actual list while the other is removeDuplicated list which tells your program which entries to keep unique. 一个是实际列表,另一个是removeDuplicated列表,它告诉程序哪些条目保持唯一。
Also, you can maintiain the order by either using a LinkedList or a ArrayList. 另外,您可以使用LinkedList或ArrayList维护顺序。
I would create another array without duplicates. 我将创建另一个没有重复的数组。
Create another array(list2) and add elements from source array(list1) if list2 does not contain the same element except for "d". 如果list2除“ d”之外不包含相同元素,则创建另一个array(list2)并从源array(list1)添加元素。
ArrayList<String> list1;
ArrayList<String> list2;
for(int i=0;i<list1.size();i++) {
String element = list1.get(i);
if((!element.equals("d")) && (!list2.contains(element))) {
list2.add(element);
}
}
I do not want to write code if this is a homework exercise for you. 如果这是您的家庭作业,我不想编写代码。
Do the following. 请执行下列操作。
Define a HashSet
of not allowed items ('a','b','c')
and an empty HashSet
called elimination set. 限定
HashSet
不允许项('a','b','c')
和一个空HashSet
称为消除集。
Iterate through the ArrayList
. 遍历
ArrayList
。
Test the item against elimination HashSet
and remove the item from ArrayList
if the item is in elimination set. 针对消除
HashSet
测试该项目,如果该项目在消除集中,则将其从ArrayList
中删除。
Test the item against not allowed HashSet
and add the item to elimination HashSet
if the item is in not allowed set. 针对不允许的
HashSet
测试该项目,如果该项目处于不允许的集合中,则将该项目添加到消除HashSet
中。
Time complexity is O(n) where n is length of ArrayList
. 时间复杂度为O(n) ,其中n是
ArrayList
长度。
I would create 2 arrayList. 我将创建2 arrayList。 One with the values and one with the values you want to remove.
一种带有要删除的值,另一种带有要删除的值。 Simply do a removal with the list of the values you no longer want.
只需使用不再需要的值列表进行删除。
public class SOTest
{
public static void main(String[] args)
{
String [] strAr = {"a", "b", "c", "d", "d", "a", "b", "b", "d", "c"};
String [] removeAr = {"a", "b"};
ArrayList<String> arList = new ArrayList<String>(Arrays.asList(strAr));
ArrayList<String> removeList = new ArrayList<String>(Arrays.asList(removeAr));
arList.removeAll(removeList);
for(String s : arList)
System.out.println(s);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.