2014-11-05 60 views
0

我有兩個列表填充對象元素。使用這兩個列表,我想創建另一個只包含它們之間不常見元素的列表。如何顯示兩個對象列表之間的唯一元素?

我試着使用迭代器:

for(Row currentRowObject: currentRow) { 
    for (Iterator<Row> newError = newErrorRow.iterator(); newError.hasNext();) { 
     Row rowObject = newError.next(); 
     if (rowObject.getAll().equals(currentRowObject.getAll())) { 
      newError.remove(); 
     } 
    } 
} 

我跑在此之後,newError列表被完全移除。我檢查了兩個列表是不同的,它們的大小不同,並且這兩個列表中有不同的對象。

我該如何解決這個問題?

回答

2

在邏輯格式(不是Java)解釋:

UncommonRows = (currentRow union newErrorRow) - (currentRow intersection newErrorRow) 

這裏是用Java做的一個快速和骯髒的方式。希望評論解釋我所做的。

Set<Row> uncommonRows=new HashSet<Row>(currentRow); 
uncommonRows.addAll(newErrorRow); //at this point uncommonRows contains all the Rows 
Set<Row> retained=new HashSet<Row>(currentRow); 
retained.retainAll(newErrorRow); //retained contains all rows that are in both sets. 
uncommonRows.removeAll(retained) ; // at this point uncommonRows contains the uncommon Rows 
+0

這樣做後,清單仍然是空的.... – 2014-11-05 16:34:17

+1

@JohnSmith你可以上傳你如何定義你的類行。你必須有相等的(Object o)和hashCode()方法重寫(使它們唯一),這個鏈接應該可以幫助你[http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding -equals-and-hashcode-in-java](http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) – nafas 2014-11-05 16:36:22

+0

@約翰史密斯順便說一句,你打印出罕見的行:) – nafas 2014-11-05 16:38:54

2

您可以使用集retainAll財產&使用removeAll

Set <Row> rows1 = new HashSet(currentRow); 
Set <Row> rows2 = new HashSet(newErrorRow); 
rows1.retainAll(rows2); // rows1 now contains only elements in both set ! 
rows2.removeAll(rows1); // rows2 now contains only the unique elements ! 
+0

+ 1 /你可以初始化'row1'爲'設置 ROW1 =新的HashSet <> (currentRow);'並用'newErrorRow'對'row2'做同樣的操作。並且還修復了錯誤**中的錯誤**全部保留** n **全部。 – vefthym 2014-11-05 16:24:12

+0

@vefthym謝謝修復它! ... – StackFlowed 2014-11-05 16:32:14

+0

我剛剛看到OP要求尋找不尋常的元素! – vefthym 2014-11-05 16:37:44

1

使用java8你可以這樣做:

final List<Row> allErrors = new ArrayList<>(); 
    allErrors.addAll(currentRow); 
    allErrors.addAll(newErrorRow); 

然後:

final List<Row> result = allErrors.stream().filter(p -> Collections.frequency(allErrors, p) == 1) 
      .collect(Collectors.toList()); 
相關問題