Kotlin: Lambdas, range, map, filter and reduce/fold

穿精又带淫゛_ 提交于 2019-12-13 11:23:52

问题


Using the functions such as lambdas, range, map, filter and reduce/fold, calculate the sum of numbers between 1 and 1000 which are divisible by 5 or 3 and print the result.


回答1:


We can do the following:

println((1..1000).filter{ it % 3 == 0 || it % 5 == 0 }.reduce{sum, element -> sum + element})

Instead of reduce we could use sum as well which would look like this:

println((1..1000).filter{ it % 3 == 0 || it % 5 == 0 }.sum())


来源:https://stackoverflow.com/questions/55132231/kotlin-lambdas-range-map-filter-and-reduce-fold

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!