Scala到Java(函数式编程) [英] Scala to Java (functional programming)
问题描述
我被要求将一些Scala代码翻译成Java课程。但是,分配的要求是Java 8和外部库,例如功能性Java 和完全懒惰,不允许。 Scala中的行是:
charges.groupBy(_。cc).values.map(_。reduce(_ combine _ ))。toList
我已经可以写 groupBy
和值
但 .map
和 _。reduce
仍然逃避我。我查看了这两个库的源代码以及Scala源代码,试图找到一些可以帮助我将它们放在一起的东西,但是我一直未能取得任何进展。
GroupBy实现如下:
public Map< CreditCard,列表与LT;电荷>> groupBy(List< Charge> list)
{
Map< CreditCard,List< Charge>> map = new TreeMap< CreditCard,List< Charge>>();
(费用c:列表)
{
列表<费用> group = map.get(c.cc);
if(group == null)
{
group = new ArrayList();
map.put(c.cc,group);
}
group.add(c);
}
返回地图;
您可以使用 Google Guava 。它不需要java8。你会特别对调用 FluentIterable
的类感兴趣。这里有一些方法可以帮助你:
$ b
- index(Function keyFunction) - 用于为每个值生成密钥的函数
- transform(函数函数) - 将{函数}应用于这个流畅迭代的每个元素
和还有更多。
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;
}
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.
这篇关于Scala到Java(函数式编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!