In a 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;
}
}
Its purpose is to hold String
and Integer
values. Additionally, the class implements the Comparable
interface so that it's sortable.
The main container for Inner
class instances is ArrayList
:
ArrayList<Inner> cont = new ArrayList<>();
After filling this list 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, the compiler produces an error:
Bad return type in lambda expression: String cannot be converted to Inner
Is there any way to do this, still using streams?
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(" "));