如何显示两个对象列表之间的唯一元素?

时间:2014-11-05 16:13:52

标签: java eclipse eclipse-rcp

我有两个填充了对象元素的列表。使用这两个列表,我想创建另一个列表,其中只包含它们之间的不常见元素。

我尝试使用迭代器:

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列表已完全删除。我检查了两个列表是不同的,它们的大小不同,并且这两个列表之间的对象不同。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您可以使用套件retainAll属性&amp;使用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 !

答案 1 :(得分: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

答案 2 :(得分: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());