Java - 设置<objecta> removeAll(设置<objectb>)不起作用

时间:2016-06-24 13:24:51

标签: java set

我有一个Set A和一个Set B.我想要做的是设置A - 使用设置B. 设置A.removeAll(设置B)。

我已经覆盖了equals()和hashCode()函数,如下所示:

GooleGeometryPoint.class

@Override
public int hashCode() {
    return new HashCodeBuilder(17, 31) // two randomly chosen prime numbers
                    .append(postalcode)
                    .toHashCode();
}

@Override
public boolean equals(Object obj) {

    if (!(obj instanceof GoogleGeometryPoint))
        return false;
    if (obj == this)
        return true;

    if(postalcode.equals(((GoogleGeometryPoint) obj).getPostalcode())) {
        return true;
    }
    return false;
}

Main.class

Set<GoogleGeometryPoint> onlinePostalcodes;
Set<GoogleGeometryPoint> offlinePostalcodes;

//Get all complaints
        complaints =
                CsvParser.parseCsv(Constants.FILE_KLACHTEN_CSV)
                        .stream()
                        .map(k -> CsvParser.mapToKlachtModel(k.toString()))
                        .collect(Collectors.toList());

        //Get all offline postalcodes with coordinates
        offlinePostalcodes =
                CsvParser.parseCsv(Constants.FILE_POSTAL_CSV)
                        .stream()
                        .map(p -> CsvParser.mapToGoogleGeometryPoint(p.toString()))
                        .collect(Collectors.toSet());


        //Copy complaints into set
        onlinePostalcodes = complaints
                .stream()
                .map(e -> new GoogleGeometryPoint(e.getPostalcode(), e.getStreet(), e.getCity()))
                .collect(Collectors.toSet());


        //Remove all the postalcodes that are already offline available
        onlinePostalcodes
                .stream()
                .filter(e -> e.getPostalcode() != null)
                .collect(Collectors.toSet())
                .removeAll(offlinePostalcodes);

在调用removeAll()方法之后,onlinePostalcodes似乎包含与以前相同的对象,没有删除任何内容。我的逻辑有什么问题吗?任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:3)

使用.collect(Collectors.toSet())创建一个删除的新对象。您不会更改onlinePostalcodes。也许你打算写

    onlinePostalcodes = onlinePostalcodes
            .stream()
            .filter(e -> e.getPostalcode() != null)
            .collect(Collectors.toSet());

    onlinePostalcodes.removeAll(offlinePostalcodes);