在lambda表达式中的返回类型,Reduce函数

huangapple go评论84阅读模式
英文:

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&lt;Inner&gt;
    {
        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&lt;Inner&gt; cont = new ArrayList&lt;&gt;();

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(&quot; &quot;,(String r, Inner e)-&gt;{return r+=e.s+&quot; &quot;;});

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() 来获取 Inners。而且最好使用 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 -&gt; e.s).collect(Collectors.joining(&quot; &quot;));

huangapple
  • 本文由 发表于 2020年10月17日 21:16:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64402893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定