2013-10-09 53 views
0

我正在尋找一個很好的方法來從列表中刪除重複項。從列表中刪除重複項目<String[]>

List<String[]> rowList = new ArrayList(); 
    rowList.add(new String[]{"1","a", "abc"}); 
    rowList.add(new String[]{"2","b", "def"}); 
    rowList.add(new String[]{"3","c", "ghi"}); 
    rowList.add(new String[]{"4","a", "jkl"}); 
    rowList.add(new String[]{"5","d", "mno"}); 
    rowList.add(new String[]{"6","e", "pqr"}); 
    rowList.add(new String[]{"7","b", "stu"}); 

從這rwoList,我只想條目:1,2,3,5和6。這意味着我只有一個intrest的柱,在這種情況下塔2(A,B,C,.. ) 這只是一個簡單的例子,我必須處理有300列和300000行的表格。另一個重要的觀點是,我不會放鬆名單中的方向。

注意:我收到來自csv文件的數據。

+1

http://stackoverflow.com/questions/10370750/removing-duplicate-elements-from-a-list – Andy897

+1

每一個常見的問題。似乎沒有努力,谷歌。所以下來投票。 – Andy897

+0

你從數據庫中檢索這些數據嗎?重複是否合法?還是表明不一致? – Fildor

回答

1
List<String[]> rowList = new ArrayList<String[]>(); 
    rowList.add(new String[]{"1","a", "abc"}); 
    rowList.add(new String[]{"2","b", "def"}); 
    rowList.add(new String[]{"3","c", "ghi"}); 
    rowList.add(new String[]{"4","a", "jkl"}); 
    rowList.add(new String[]{"5","d", "mno"}); 
    rowList.add(new String[]{"6","e", "pqr"}); 
    rowList.add(new String[]{"7","b", "stu"}); 

    Set<String[]> s = new TreeSet<String[]>(new Comparator<String[]>() { 
     @Override 
     public int compare(String[] o1, String[] o2) { 
       return o1[1].compareTo(o2[1]); 
     } 
    }); 

通過增加設置"s"

刪除重複項
s.addAll(rowList); 
    List<Object> res = Arrays.asList(s.toArray()); 

打印你的結果

for (Object object : res) { 
     String[] array = (String[])object; 
     System.out.println(array[0]+" "+ array[1] +", "+array[2]); 
    } 

輸出

1 a, abc 
2 b, def 
3 c, ghi 
5 d, mno 
6 e, pqr 
+0

由於我瞭解OP,訂單不得改變。這將按照關鍵列排序,不是嗎? – Fildor

+0

我建議使用[LinkedHashSet](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html),因爲:「設置界面的哈希表和鏈表實現,可預測的迭代次序。「 – Fildor

+0

@Fildor是的你是對的。爲了使用LinkedHashSet,我們需要使用Comparator或Comparable的實現。我認爲用String []會很複雜。 – Prabhakaran

0

創建自定義方法isContain(List<String[]> rowList, String string)

private static boolean isContain(List<String[]> rowList, String secStr) { 
    for (String[] strings : rowList) { 
     if(strings[1].equals(secStr)){ 
      return true; 
     } 
    } 
    return false; 
} 

入住此方法前添加項目List刪除重複項,如:

List<String[]> rowList = new ArrayList(); 
    String[] sts= new String[]{"1", "a", "abc"}; 
    boolean contain= isContain(rowList,sts[1]); 
    if(!contain){ 
     rowList.add(sts); 
    }