繁体   English   中英

Java Streams 中 lambda 函数的集合

[英]Collection of lambda functions in Java Streams

我有一个流函数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;
        }

我还没有测试过这段代码,但理论上它应该可以工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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