繁体   English   中英

从ArrayList中删除重复项 <ArrayList<String> &gt;对象

[英]Remove Duplicates from ArrayList<ArrayList<String>> Object

我有一个ArrayList,它有一个嵌套的字符串ArrayList,我想从中删除重复项。 我知道如果我一直想删除重复项,我不应该使用ArrayList,但在某些情况下重复是有效的。 从嵌套的ArrayList中删除重复项的最佳方法是什么?

例如,我想执行一些转换的Java:

[[duplicate], [duplicate], [duplicate], [unique1], [unique2]]

至:

[[duplicate], [unique1], [unique2]]

要删除ArrayList中的重复项,您可以执行此操作

yourList = new ArrayList<String>(new LinkedHashSet<String>(yourList));

使用LinkedHashSet而不是HashSet可确保保留原始列表的顺序。


关于你的评论:

这是一个将[[1,2,3], [1,2], [3], [1,2]][[1,2,3], [1,2], [3]]

Set<String> seen = new HashSet<String>();
for (List<String> l : strLists) {
    for (Iterator<String> iter = l.iterator(); iter.hasNext(); )
        if (!seen.add(iter.next()))
            iter.remove();

    // If you want to remove lists that end up empty:
    if (l.isEmpty())
        strLists.remove(l);
}
import java.util.Arrays;

public class RunDuplicate
{
public RunDuplicate()
{
super();
}

public static void main(String[] args)
{
String[] duplicates = new String[] {"duplicate","duplicate","duplicate","unique1","unique2"};

Arrays.sort(duplicates);

int k = 0;

for (int i = 0; i < duplicates.length; i++)
{
if (i > 0 && duplicates[i].equals(duplicates[i -1]))
continue;

duplicates[k++] = duplicates[i];
}

String[] unique = new String[k];

System.arraycopy(duplicates, 0, unique, 0, k);

//test that unique contains no duplicate strings
for (int i = 0; i < unique.length; i++)
System.out.println(unique[i]);
}
}

aioobe说,使用一个集合,除了你将它放在一个循环,因为你有一个两个demisional数组:

Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:yourList) {
    set.addAll (list);
}
ArrayList<String> uniqueList = new ArrayList<String>(set);

你可以这样做:

for (Iterator<ArrayList<String>> it = myListInList.iterator(); it.hasNext();)
{ 
   ArrayList<String> current = it.next();
   HashSet h = new HashSet(current);
   current.clear();
   current.addAll(h);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM