Java-8流表达式将“OR”的几个枚举值组合在一起 [英] Java-8 stream expression to 'OR' several enum values together

查看:408
本文介绍了Java-8流表达式将“OR”的几个枚举值组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在foreach循环中聚合了一堆枚举值(与序数值不同)。

I am aggregating a bunch of enum values (different from the ordinal values) in a foreach loop.

   int output = 0;
   for (TestEnum testEnum: setOfEnums) {
        output |= testEnum.getValue();
   }

有没有办法在流API中执行此操作?

Is there a way to do this in streams API?

如果我在 Stream< TestEnum> 中使用这样的lambda:

If I use a lambda like this in a Stream<TestEnum> :

   setOfEnums.stream().forEach(testEnum -> (output |= testEnum.getValue());

我得到一个编译时错误,说'在lambda中使用的变量应该是有效的最终'。

I get a compile time error that says, 'variable used in lambda should be effectively final'.

推荐答案

谓词表示一个布尔值函数,你需要使用流的reduce方法来聚合一堆枚举值。

Predicate represents a boolean valued function, you need to use reduce method of stream to aggregate bunch of enum values.

如果我们考虑你将HashSet命名为SetOfEnums:

if we consider that you have HashSet as named SetOfEnums :

    //int initialValue = 0; //this is effectively final for next stream pipeline if you wont modify this value in that stream
    final int initialValue = 0;//final
    int output = SetOfEnums.stream()
                     .map(TestEnum::getValue)
                     .reduce(initialValue, (e1,e2)-> e1|e2);

这篇关于Java-8流表达式将“OR”的几个枚举值组合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆