我有一个ArrayList,它有一个嵌套的字符串ArrayList,我想从中删除重复项。我知道如果我一直想删除重复项,我不应该使用ArrayList,但在某些情况下重复是有效的。从嵌套的ArrayList中删除重复项的最佳方法是什么?
例如,我想执行一些可以转换的Java:
[[duplicate], [duplicate], [duplicate], [unique1], [unique2]]
以
[[duplicate], [unique1], [unique2]]
答案 0 :(得分:11)
要删除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);
}
答案 1 :(得分:3)
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]);
}
}
答案 2 :(得分:2)
aioobe说,使用一个集合,除了你将它放在一个循环中,因为你有一个两个demisional数组:
Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:yourList) {
set.addAll (list);
}
ArrayList<String> uniqueList = new ArrayList<String>(set);
答案 3 :(得分:0)
你可以这样做:
for (Iterator<ArrayList<String>> it = myListInList.iterator(); it.hasNext();) { ArrayList<String> current = it.next(); HashSet h = new HashSet(current); current.clear(); current.addAll(h); }
for (Iterator<ArrayList<String>> it = myListInList.iterator(); it.hasNext();) { ArrayList<String> current = it.next(); HashSet h = new HashSet(current); current.clear(); current.addAll(h); }