简体   繁体   中英

Java : Factorization using predicate [on hold]

Can we factor one more this code:

protected Comparator<Personne> getComparator() {
    Comparator<Personne> comparator1 = LambdaUtil.wrapComparator(
                     personne -> personne != null && personne.Y() != null ?
                     APIPersonne.getAliasedName(personne.Y().getX()) : 
                     null, 
                String.CASE_INSENSITIVE_ORDER);

    Comparator<Personne> comparator2 = LambdaUtil.wrapComparator(
                     personne -> personne != null && personne .getY() != null ? 
                     APIPersonne.getAliasedName(personne.getY()) : 
                     null, 
                String.CASE_INSENSITIVE_ORDER);

    Comparator<Personne> comparator3 = LambdaUtil.wrapComparator(
                APIPersonne::getZ(), String.CASE_INSENSITIVE_ORDER);

    return comparator1.thenComparing(comparator2).thenComparing(comparator3);
}

Knowing that getY() and getX throw exceptions.

If you meant using Predicate specifically, you can abstract that out as:

Predicate<Personne> predicate = personne -> personne != null && personne.Y() != null;

and further use it as:

Comparator<Personne> comparator1 = LambdaUtil.wrapComparator(
            personne -> predicate.test(personne) ? APIPersonne.getAliasedName(personne.Y().getX()) : null,
            String.CASE_INSENSITIVE_ORDER);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM