java - Java Streams 中 lambda 函数的集合

标签 java java-8 java-stream apache-kafka-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()]);
}

关于java - Java Streams 中 lambda 函数的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902587/

相关文章:

java - 如何在Java中使用保留关键字声明参数名称

java - 是否可以使用 Optionals 为不同的 Java 类型返回 first not null 值?

Java 8 流 - 通过比较两个列表进行过滤

Java 8 lambdas 查找 map 列表的平均值

java - 为什么打印语句不适用于请求调度程序的转发方法?

java - App Engine 的 URLFetch : http GET works locally but not when deployed to GAE on a specific URL

java - 部署在kubernetes上时微服务中服务间通信的连接超时问题

java - 是否可以将流收集到两个收集器中

java - 在由 Stream 外部的对象确定的流上返回 min

Java - 创建具有给定范围的 IntStream,然后使用映射函数随机化每个元素