代码之家  ›  专栏  ›  技术社区  ›  JiKra

创建单独的谓词

  •  1
  • JiKra  · 技术社区  · 7 年前

    people.stream()
                .filter(person -> peopleTime.stream().anyMatch(time ->
                        (!person.getValidTo().isPresent() || time.getValidFrom().isBefore(person.getValidTo().get()) || time.getValidFrom().isEqual(person.getValidTo().get()))
                                && (!time.getValidTo().isPresent() || time.getValidTo().get().isAfter(person.getValidFrom()) || time.getValidTo().get().isEqual(person.getValidFrom()))))
    

    我试图创建一些双谓词并使用它,但anyMatch需要单个谓词。Person类扩展Time类。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jeremy Grand    7 年前

    据我所知,你基本上有:

    public abstract static class MyDate {
        public abstract boolean isBefore(MyDate other);
        public abstract boolean isAfter(MyDate other);
        public abstract boolean isEqual(MyDate other);
    }
    public static abstract class Time {
        public abstract Optional<MyDate> getValidTo();
        public abstract Optional<MyDate> getValidFrom();
    }
    
    public static abstract class Person extends Time {
    }
    

    (好吧,我暂时不谈实现)。

    如果创建以下类:

    public static class TimePersonPredicate implements Predicate<Time> {
    
        private final Person person;
        public TimePersonPredicate(Person person) {
            this.person = person;
        }
        @Override
        public boolean test(Time time) {
            return (!person.getValidTo().isPresent() || time.getValidFrom().get().isBefore(person.getValidTo().get()) || time.getValidFrom().get().isEqual(person.getValidTo().get()))
                    && (!time.getValidTo().isPresent() || time.getValidTo().get().isAfter(person.getValidFrom().get()) || time.getValidTo().get().isEqual(person.getValidFrom().get()));
        }
    
    }
    

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        List<Time> peopleTime = new ArrayList<>();
        people.stream()
            .filter(person -> peopleTime.stream().anyMatch(new TimePersonPredicate(person) ))...
    }
    

    这就是你想要的吗?