英文:
Return type in lambda expression, Reduce function
问题
在静态方法中,我实现了内部类:
class Inner implements Comparable<Inner>
{
Integer v;
String s;
public Inner(Integer a, String st) {v = a; s= st; }
@Override
public int compareTo(Inner o) {
int result = Integer.compare(this.v, o.v);
if (result == 0)
return (String.CASE_INSENSITIVE_ORDER.compare(this.s, o.s));
else
return result;
}
}
它的目的是保存字符串和整数值。此外,该类实现了Comparable接口,以便进行排序。
存储Inner类实例的主要容器是ArrayList:
ArrayList<Inner> cont = new ArrayList<>();
在填充动态数组之后,我想对其进行排序,然后连接字符串值,所有这些都使用Streams实现:
String res = cont.stream().sorted(Inner::compareTo).reduce(" ", (String r, Inner e) -> {return r += e.s + " ";});
不幸的是,编译器报错:
在lambda表达式中的错误返回类型:无法将String转换为Inner
是否有办法解决这个问题,仍然使用Streams呢?
谢谢。
英文:
in static method I've implemented inner class:
class Inner implements Comparable<Inner>
{
Integer v;
String s;
public Inner(Integer a, String st) {v = a; s= st; }
@Override
public int compareTo(Inner o) {
int result = Integer.compare(this.v,o.v);
if (result == 0)
return (String.CASE_INSENSITIVE_ORDER.compare(this.s,o.s));
else
return result;
}
}
It's purpose's to hold String and Integer values. Aditionally class implements Comparable interface, so that it's sortable
Main container for Inner's class instances is ArrayList
ArrayList<Inner> cont = new ArrayList<>();
After filling dynamic array I want to sort it and next concat String values, all of this using Streams.
String res = cont.stream().sorted(Inner::compareTo).reduce(" ",(String r, Inner e)->{return r+=e.s+" ";});
Unfortunately, compilator sends me error:
Bad return type in lambda expression: String cannot be converted to Inner
Is any way to solve it, still usings Streams?
Regards
答案1
得分: 3
你应该在 reduce 之前使用 .map()
来获取 Inner
的 s
。而且最好使用 Collectors.joining
来用分隔符连接字符串。
cont.stream().sorted(Inner::compareTo).map(e -> e.s).collect(Collectors.joining(" "));
英文:
You should take the s
of Inner
using .map()
before reduce. And it's better to use Collectors.joining
to join the string with delimiter
cont.stream().sorted(Inner::compareTo).map(e -> e.s).collect(Collectors.joining(" "));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论