2014-11-05 62 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()); 
相关问题