![](/img/trans.png)
[英]How to remove duplicates ArrayList from an ArrayList of ArrayList
[英]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.