Коллекция лямбда-функций в Java Streams - PullRequest
2 голосов
/ 29 апреля 2019

У меня есть функция потока KStream<K, V>[] branch(final Predicate<? super K, ? super V>... predicates). Я хотел создать список предикатов динамически. Это возможно?

       KStream<Long, AccountMigrationEvent>[] branches = stream
           .map((key, event) -> enrich(key, event))
           .branch(getStrategies());

        [...]

        private List<org.apache.kafka.streams.kstream.Predicate<Long, AccountMigrationEvent>> getStrategies() {
            ArrayList<Predicate<Long, AccountMigrationEvent>> predicates = new ArrayList<>();
            for (MigrationStrategy strategy : strategies) {
                predicates.add(new org.apache.kafka.streams.kstream.Predicate<Long, AccountMigrationEvent>() {
                    @Override
                    public boolean test(Long key, AccountMigrationEvent value) {
                        return strategy.match(value);
                    }
                });

            }
            return predicates;
        }

1 Ответ

2 голосов
/ 29 апреля 2019

Я не тестировал этот код, но теоретически он должен работать:

//All the predicates mentioned in here are of type org.apache.kafka.streams.kstream.Predicate
private Predicate<Long, AccountMigrationEvent>>[] getStrategies() {

  List<Predicate<Long, AccountMigrationEvent>> predicates = strategies.stream()
            .map(strategy -> (Predicate<Long, AccountMigrationEvent>>) (key, value) -> strategy.matches(value))
            .collect(toList());

    // branch() method on KStream requires an array so we need to transform our list
    return predicates.toArray(new Predicate[predicates.size()]);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...