如何在anyMatch()java 8流中应用复合BiPredicate

时间:2015-11-02 16:02:26

标签: java collections java-8 java-stream

我有两个列表。我从数据库创建一个,从Csv文件创建一个。现在我想收集包含数据库和csv文件的列表中的记录。我写了如下代码

BiPredicate<Trainee, Trainee> sameTrainee = (dbTrainee, csvTrainee) -> {

    String dbTraineeFirstName = dbTrainee.getFirstName();
    String dbTraineeLastName = dbTrainee.getLastName();
    String dbTraineeEmail = dbTrainee.getEmail();
    LocalDateTime dbTraineeCompletionDate = dbTrainee.getSessionDateTime();
    String text = dbTraineeCompletionDate.format(DATE_TIME_FORMATTER); 
    LocalDateTime dbTraineeSessionDateTime = LocalDateTime.parse(text);
    String dbTraineePhoneNumber = dbTrainee.getPhoneNumber();
    String dbTraineeSsn = dbTrainee.getSocialSecurityLastFour();
    String dbTraineeStreetOne = dbTrainee.getStreetOne();
    String dbTraineeCity = dbTrainee.getCity();

    String csvTraineeFirstName = csvTrainee.getFirstName();
    String csvTraineeLastName = csvTrainee.getLastName();
    String csvTraineeEmail = csvTrainee.getEmail();
    LocalDateTime csvTraineeSessionDateTime = csvTrainee.getSessionDateTime();
    String csvTraineePhoneNumber = csvTrainee.getPhoneNumber();
    String csvTraineeSsn = csvTrainee.getSocialSecurityLastFour();
    String csvTraineeStreetOne = csvTrainee.getStreetOne();
    String csvTraineeCity = csvTrainee.getCity();

    int dbTraineeSsnLength = dbTraineeSsn.length();
    int csvTraineeSsnLength = csvTraineeSsn.length();

    if (dbTraineeSsnLength != csvTraineeSsnLength) {
        if (dbTraineeSsnLength == 4 && dbTraineeSsn.startsWith("0")) {
            String dbTraineeSsnLast3Digits = dbTraineeSsn.substring(dbTraineeSsn.length() - 3);
            if (csvTraineeSsnLength == 3 && csvTraineeSsn.endsWith(dbTraineeSsnLast3Digits)) {
                csvTraineeSsn = "0" + csvTraineeSsn;
            }
        }
    }

    return dbTraineeFirstName.equals(csvTraineeFirstName) 
            && dbTraineeLastName.equals(csvTraineeLastName)
            && dbTraineeEmail.equals(csvTraineeEmail) 
            && dbTraineeSessionDateTime.equals(csvTraineeSessionDateTime)
            && dbTraineePhoneNumber.equals(csvTraineePhoneNumber)
            && dbTraineeSsn.equals(csvTraineeSsn) 
            && dbTraineeStreetOne.equals(csvTraineeStreetOne)
            && dbTraineeCity.equals(csvTraineeCity);
};

并称之为

List<Trainee> foundInBothList = dbMonthlyTraineeList.stream()
                    .filter(dbTrainee -> csvTraineeList.stream()
                        .anyMatch(csvTrainee -> {
                            return sameTrainee.test(dbTrainee, csvTrainee);
                        })
                    ).collect(Collectors.toList());

List<Trainee> notInFileList = dbMonthlyTraineeList.stream()
                    .filter(dbTrainee -> csvTraineeList.stream()
                        .noneMatch(csvTrainee -> {
                            return sameTrainee.test(dbTrainee, csvTrainee);
                        })
                    ).collect(Collectors.toList());

工作正常。但是,因为我的BiPredicate变得越来越不整洁。所以我创建了一个类并收集了如下所示的集合中的所有谓词

public class PlcbMonthlyReportStatisticsBiPredicates {

    public static BiPredicate<Trainee, Trainee> isValidFirstName() {
        return (dbTrainee, csvTrainee) -> {
            String dbTraineeFirstName = dbTrainee.getFirstName();
            String csvTraineeFirstName = csvTrainee.getFirstName();
            return dbTraineeFirstName.equals(csvTraineeFirstName);
        };
    }

    public static BiPredicate<Trainee, Trainee> isValidSsn() {
        return (dbTrainee, csvTrainee) -> {
            String dbTraineeSsn = dbTrainee.getSocialSecurityLastFour();
            String csvTraineeSsn = csvTrainee.getSocialSecurityLastFour();
            ...
            return dbTraineeSsn.equals(csvTraineeSsn);
        };
    }

    ....

    public static List<BiPredicate<Trainee, Trainee>> getAllBiPredicates() {

        List<BiPredicate<Trainee, Trainee>> allPredicates = Arrays.asList(
                isValidFirstName(),
                isValidSsn(),
                ... 
        );  
        return allPredicates;
    }
}

现在我收集所有谓词但是如何在我的anyMatch()和noneMatch()中应用这些谓词。我试过这个但是cources得到错误

List<Trainee> foundInBothList1 = dbMonthlyTraineeList.stream()
    .filter(dbTrainee -> csvTraineeList.stream()
        .anyMatch(csvTrainee -> {
            List<BiPredicate<Trainee, Trainee>> allBiPredicates = getAllBiPredicates();
            return allBiPredicates.stream().reduce(BiPredicate::and).orElse((x,y)->true);  //error

        })
    ).collect(Collectors.toList());

我该如何应用呢?我的做法是对的吗?

**修改

@Entity
public class Trainee {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

    private LocalDateTime sessionDateTime;
    private String firstName;
    ....

    @Override
    public boolean equals(Object otherObject) {

        // Are the same?
        if (this == otherObject) {
            return true;
        }
        // Is otherObject a null reference?
        if (otherObject == null) {
            return false;
        }
        // Do they belong to the same class?
        if (this.getClass() != otherObject.getClass()) {
            return false;
        }

        // Get the reference of otherObject in a otherTrainee variable
        Trainee otherTrainee = (Trainee)otherObject;

        LocalDateTime dbTraineeCompletionDate = this.getSessionDateTime();
        String text = dbTraineeCompletionDate.format(DATE_TIME_FORMATTER); 
        LocalDateTime dbTraineeSessionDateTime = LocalDateTime.parse(text);

        String dbTraineeSsn = this.socialSecurityLastFour;
        String csvTraineeSsn = otherTrainee.getSocialSecurityLastFour();

        int dbTraineeSsnLength = dbTraineeSsn.length();
        int csvTraineeSsnLength = csvTraineeSsn.length();

        if (dbTraineeSsnLength != csvTraineeSsnLength) {
            if (dbTraineeSsnLength == 4 && dbTraineeSsn.startsWith("0")) {
                String dbTraineeSsnLast3Digits = dbTraineeSsn.substring(dbTraineeSsn.length() - 3);
                if (csvTraineeSsnLength == 3 && csvTraineeSsn.endsWith(dbTraineeSsnLast3Digits)) {
                    csvTraineeSsn = "0" + csvTraineeSsn;
                }
            }
        }

        boolean isEqual = (this.firstName.equals(otherTrainee.firstName)
            && this.lastName.equals(otherTrainee.lastName)
            && this.email.equals(otherTrainee.email) 
            && dbTraineeSessionDateTime.equals(otherTrainee.sessionDateTime)
            && this.phoneNumber.equals(otherTrainee.phoneNumber)
            && dbTraineeSsn.equals(csvTraineeSsn) 
            && this.streetOne.equals(otherTrainee.streetOne)
            && this.city.equals(otherTrainee.city)
        );

        return isEqual;
    }

    @Override
    public int hashCode() {

        int hash = 37;
        int code = 0;

        code = (firstName == null ? 0 : firstName.hashCode());
        hash = hash * 59 + code;

        code = (lastName == null ? 0 : lastName.hashCode());
        hash = hash * 59 + code;

        code = (email == null ? 0 : email.hashCode());
        hash = hash * 59 + code;

        code = (sessionDateTime == null ? 0 : sessionDateTime.hashCode());
        hash = hash * 59 + code;

        code = (phoneNumber == null ? 0 : phoneNumber.hashCode());
        hash = hash * 59 + code;

        code = (socialSecurityLastFour == null ? 0 : socialSecurityLastFour.hashCode());
        hash = hash * 59 + code;

        code = (streetOne == null ? 0 : streetOne.hashCode());
        hash = hash * 59 + code;

        code = (city == null ? 0 : city.hashCode());
        hash = hash * 59 + code;

        return hash;

    }
}

编辑2(在覆盖hascode()和equals()之后) ------------------------------------------------- < /强>

在两者中找到:

List<Trainee> foundInBothList1 = dbMonthlyTraineeList.stream()
    .filter(dbTrainee -> csvTraineeList.stream()
        .anyMatch(csvTrainee -> {
            return allBiPredicates.stream().reduce(BiPredicate::and).orElse((x,y)->true).test(dbTrainee, csvTrainee);

        })
    ).collect(Collectors.toList());

    List<Trainee> foundInBothList = new ArrayList<>(dbMonthlyTraineeList);
    //foundInBothList.retainAll(new HashSet<>(csvTraineeList));
    foundInBothList.retainAll(csvTraineeList);

在数据库中找到但不是在CSV

中找到
List<Trainee> notInCsvFileList1 = dbMonthlyTraineeList.stream()
    .filter(dbTrainee -> csvTraineeList.stream()
        .noneMatch(csvTrainee -> {
            return allBiPredicates.stream().reduce(BiPredicate::and).orElse((x,y)->true).test(dbTrainee, csvTrainee);
        })
    ).collect(Collectors.toList());

//find out that elements of dbMonthlyTraineeList which is not present in arraylist(csvTraineeList).
List<Trainee> notInCsvFileList = new ArrayList<>(dbMonthlyTraineeList);
notInCsvFileList.removeAll(csvTraineeList);

1 个答案:

答案 0 :(得分:2)

看起来你在想这个。为什么不用您的equals双谓词代码覆盖sameTrainee? (别忘了也覆盖hashCode。)

执行此操作后,您可以使用以下命令保留两个列表中的Trainee

Set<Trainee> foundInBothList = new HashSet<>(dbMonthlyTraineeList);
foundInBothList.retainAll(new HashSet<>(csvTraineeList));

这个解决方案是O(n),所以它的性能比你的解决方案好很多,即O(n²)。这是因为contains操作是Set上的常量时间。

但是如果你真的想要编译你的代码,你只需要在有错误的地方调用test方法:

return allBiPredicates.stream().reduce(BiPredicate::and)
                               .orElse((x,y)->true)
                               .test(dbTrainee, csvTrainee);