使用java流时更改映射密钥数据类型



我正在尝试学习java蒸汽,为了更好地学习它,我正在尝试使用流重写现有代码。我正在尝试将列表转换为使用流式传输的地图,如下

private Map<String, List<Details>> someMethod(
Request request) {
return  Optional.ofNullable(request)
.map(request -> ((Parent) request.getProduct()).getItin())
.map(itin -> itin.getDetailsList())
.stream()
.flatMap(Collection::stream)
.collect(Collectors.toMap(Details::getId,details->details));

}

我想用Key作为String构建一个映射,但是Details::getId是Integer。如何将其转换为字符串?

这里很可能需要使用Collectors.grouping By而不是toMap:

return Optional.ofNullable(request)
.map(request -> ((Parent) request.getProduct()).getItin())
.map(itin -> itin.getDetailsList())
.stream()
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(d -> Integer.toString(d.getId()))); // the value will be List<Details>

最新更新