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;
}
groupByhas a function passed in to it too. You've just ignored that and usedc.ccdirectly. If that's acceptable forgroupBythen presumably you can do the same fprmap