我有这样的课程。
public class Foo {
private String prefix;
private String sector;
private int count;
}
给出一个foo列表:
//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 ));
而且我需要向请求返回这样的对象:
{
"1": {
"Rowa": "2",
"RowB": "1"
},
"44": {
"RowC": "1"
}
}
所以问题是:我必须用前缀来整理列表,然后在列表中以相同的行和扇区显示每个secto和itens的count(*)。我得到的是使用这样的流:
fooList.stream().
collect(
Collectors.groupingBy(
Foo::getPrefix,
Collectors.groupingBy(
Foo::getSector,
Collectors.mapping(Foo::getSector , Collectors.counting())
)
));
问题是,上面的代码是,计数是一个Long,我需要以String形式返回。我尝试使用.toString,但是它给我一个错误(可以将java.lang.String分配给java.util.stream.Collector)。
有人可以帮我吗?
您快到了,只需将Collectors.mapping
行替换为:
Collectors.summingInt(Foo::getCount))
如:
List<Foo> fooList = new ArrayList<>();
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 ));
Map<String, Map<String, Integer>> result = fooList.stream().collect(
Collectors.groupingBy(
Foo::getPrefix,
Collectors.groupingBy(
Foo::getSector,
Collectors.summingInt(Foo::getCount)
)
)
);
System.out.println(result); // prints: {44={RowC=1}, 1={Rowa=2, RowB=1}}