I have a class like this.
public class Foo {
private String prefix;
private String sector;
private int count;
}
Given a foo list:
//Args: prefix, sector, count
fooList.add(new Foo("44",,"RowC", 1 ));
fooList.add(new Foo("1",,"Rowa", 1 ));
fooList.add(new Foo("1",,"RowB", 1 ));
fooList.add(new Foo("1",,"Rowa", 1 ));
And I need to return the request an object sorted by Prefix asc like this:
{
"1": {
"Rowa": "2",
"RowB": "1"
},
"44": {
"RowC": "1"
}
}
So the problem is: I have to group the list by the prefix, and then show, every sector and the count(*) of items on the list with the same row and sector. The far that I got is using stream like this:
fooList.stream()
.collect(Collectors.groupingBy(
Foo::getPrefix,
Collectors.groupingBy(
Foo::getSector,
Collectors.mapping(Foo::getSector , Collectors.counting())
)
));
The problem is, that the code above, is that the count is a Long, and I need to return as a String. I've tried with .toString but it gives me an error (Can assign java.lang.String to java.util.stream.Collector).
UPDATE
With the help of Andreas and Naman, now I can map count as String. I just need it sorted by Prefix.
Can anyone help me?
Collectors.counting().toString()would have typeStringand putting that in a place whereCollectoris expected would throw a compile time error. UsingCollectors.collectingAndThen(Collectors.counting(), String::valueOf)would help you there.