问题
I have been asked to 'translate' some Scala code to Java for a course. However, the requirements of the assignment are that Java 8 and external libraries, such as Functional Java and Totally Lazy, are not allowed. The line in Scala is:
charges.groupBy(_.cc).values.map(_.reduce(_ combine _)).toList
I have been able to write groupBy
and values
but .map
and _.reduce
still elude me. I have looked at the source code of those two libraries as well as the Scala source to try and find something to help me with putting these together but I have not been able to make any headway.
GroupBy is implemented as follows:
public Map<CreditCard, List<Charge>> groupBy(List<Charge> list)
{
Map<CreditCard, List<Charge>> map = new TreeMap<CreditCard, List<Charge>>();
for(Charge c: list)
{
List<Charge> group = map.get(c.cc);
if(group == null)
{
group = new ArrayList();
map.put(c.cc, group);
}
group.add(c);
}
return map;
}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/35180851/scala-to-java-functional-programming