java - Java Streams 中的 lambda 函数集合
问题描述
我有一个流功能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()]);
}
推荐阅读
- c++ - 使用boost从pid获取“二进制文件”/“可执行文件”的路径?
- json - 使用 json 内容的 kotlin jvm 字符串模板
- intellij-idea - 是否可以在 LESS 中设置文件观察器以使输出文件的名称与源文件不同?
- python - 在熊猫的两列中查找关系值
- botframework - 英雄卡中没有换行的文字
- windows - cmd.exe 的环境变量存储在哪里?
- javascript - 在 ipywidgets 中创建子小部件会使用 ViewList 和 create_child_view 产生错误
- spring - 问题:ManyToMany 实体的规范查询语法
- javascript - 如何防止使用 jQuery 验证在我的输入字段中写入 url?
- android - Firebase ChildEventListener 在 Java Admin SDK 中长时间不起作用