操作 java8 流中的输出

想象一下,我们有 3 个对象的列表,其值为分钟字段:5,5,7,8


int sumOfFields = found.stream()

        .filter(abc -> minutesLessThan5(abc.getMinutes())))

        .mapToInt(abc::getMinutes)

        .sum();


// will return 10

但是我怎样才能改变我的输出,例如代替 getMinutes 我想返回我自己的值,例如 40


int sumOfFields = found.stream()

        .filter(abc -> minutesLessThan5(abc.getMinutes())))

        .mapToInt(abc ->abc.getMinutes() = 40)  //this is pseudo code what I try to achive

        .sum();


// output should be 80.


慕妹3146593
浏览 133回答 1
1回答

HUX布斯

不确定为什么人们没有对此做出回答,但正如评论中指出的那样,您可以遵循其中任何一种方法int sumOfFields = found.stream()        .filter(abc -> minutesLessThan5(abc.getMinutes())))        .mapToInt(abc -> 40) // map value to be returned as 40         .sum();或者相反,由于您将所有这些值替换为一个常数值40,您也可以使用count()并将其与常数值相乘。int sumOfFields = (int) found.stream() // casting from long to int        .filter(abc -> minutesLessThan5(abc.getMinutes())))        .count() * 40;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java