Scala to Java (functional programming)

眉间皱痕 提交于 2019-12-02 09:22:45

you can use Google Guava for this. it doesn't require java8. you would especially be interested in class which call FluentIterable. here's some methods that could help you:

  • index(Function keyFunction) - the function used to produce the key for each value
  • transform(Function function) - applies {@code function} to each element of this fluent iterable

and there are a lot more.

You'll have to iterate over the values. Ordinarily I'd suggest using a new style for loop. Something like:

for (ValuesType value : values) {
    // do your map and reduce here
}

The problem with that is you need to have access to more than one value at a time. (See discussion of .reduce(), below.) So perhaps the old style for would be better:

for (int i = 0; i < values.length - 1; i++) {
    // do something with values.get(i) or values[i] as needed
}

Point to ponder: why values.length - 1?

.map() simply transforms one thing into another. What's the transformation in this case? It's the .reduce()! So that should be easy enough.

The _ in _.reduce() is the equivalent of value in the for statement above. It's the one value that you're dealing with on this iteration.

.reduce() takes two values and does something to them to turn them into a single value. To make that work you'll need to deal with values.get(i) and values.get(i+1) somehow. And _ combine _, well, you tell me.

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