【问题标题】:Collection of lambda functions in Java StreamsJava Streams 中的 lambda 函数集合
【发布时间】:2019-04-29 11:39:40
【问题描述】:

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

【问题讨论】:

  • 您的方法需要一个数组 (...),而不是一个列表。为什么你在某些地方使用Predicate 而在其他地方使用org.apache...Predicate

标签: java java-8 java-stream apache-kafka-streams


【解决方案1】:

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

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

【讨论】:

  • 为什么首先要收集到一个列表中?为什么不在流上直接使用toArray(Predicate[]::new)
  • 除了收集到List 是不必要的之外,将集合转换为数组的标准习惯用法是predicates.toArray(new Predicate[0])。有些人认为分配与集合大小相同的数组有助于提高性能,但从未验证过这一点。 this great article 的作者实际上做了并且发现相反。因此,使用不同于零的大小只会增加潜在的错误源。
  • RealSkeptic:这是一个很好的观点,最初我这样做是为了摆脱类型检查警告,但现在我意识到我只是将它移到下面 3 行... Holger:非常有趣的文章,我从来没有预料之中!
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2020-06-27
相关资源
最近更新 更多