简体   繁体   中英

Collection of lambda functions in Java Streams

I have a stream function KStream<K, V>[] branch(final Predicate<? super K, ? super V>... predicates) . I wanted to create a list of predicates dynamically. Is that possible?

       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;
        }

I haven't tested this code but in theory it should work:

//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()]);
}

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