如何创建嵌套地图映射< string,map< string,string>>与流API
如何编写逻辑以获取map< string,map< string,string>>
使用流?
这是我尝试过的代码:
public Map<String, Map<String, String>> getData(Set<String> Ids) {
List<Events> events = repository.findAllByIdIn(Ids);
int i = 0;
return events.stream()
.sorted(Comparator.comparing(Events::getMajor).thenComparing(Events::getMinor))
.collect(Collectors.groupingBy(Events::getId,
//Error-Cannot resolve method 'getMajor()'
Collectors.mapping(cae -> cae.getMajor() + "." + cae.getMinor(),
cae.getDates().get(i).getEndDate() != null ? "Predicted" : "Not Predicted"),
Collectors.toMap())));//Error-Cannot resolve method 'toMap()'
}
那么如何在另一个地图内循环循环?
How can I write the logic to obtain a Map<String, Map<String, String>>
using streams?
Here is the code I have tried :
public Map<String, Map<String, String>> getData(Set<String> Ids) {
List<Events> events = repository.findAllByIdIn(Ids);
int i = 0;
return events.stream()
.sorted(Comparator.comparing(Events::getMajor).thenComparing(Events::getMinor))
.collect(Collectors.groupingBy(Events::getId,
//Error-Cannot resolve method 'getMajor()'
Collectors.mapping(cae -> cae.getMajor() + "." + cae.getMinor(),
cae.getDates().get(i).getEndDate() != null ? "Predicted" : "Not Predicted"),
Collectors.toMap())));//Error-Cannot resolve method 'toMap()'
}
So how do I loop through a map inside another map?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
collector
tomap()
与收集者tolist(tolist> tolist()
和()
不是参数,您需要提供信息,如何从单个流元素中提取键和值。collectors.tomap()
期望至少两个 functions :keymapper
和valueemapper
。如果可以使用tomap
,则需要使用MergeFunction
作为第三个参数来解决在同一密钥上碰撞的值。因此,您需要将
tomap()
作为第二个参数( downstream collector )放入groupingby
中。这将是 collectors 和 functions 的句法正确的结构:以及代码的外观:
Note note ,
collectors。映射()
并不是要产生地图
,而是在变换流中的元素,您可以将其视为MAP()操作未完成的操作是流管线的中间,而是在收集数据的过程中。
而且,如果我正确理解您的逻辑,则无需在此处应用
映射()
。Collector
toMap()
contrary to collectorstoList()
andtoSet()
isn't parameterless, you need to provide information how a key and a value should be extracted from a single stream element.Collectors.toMap()
expects at least two functions:keyMapper
andvalueMapper
. In case if there could be duplicates, you need to use the flavor oftoMap
which takes amergeFunction
as a third argument to resolve the values that collide on the same key.So you need to place
toMap()
as a second argument (downstream collector) into thegroupingBy
. That will be a syntactically correct structure of the collectors and functions:And that how the code might look like:
Note,
Collectors.mapping()
isn't meant to produce aMap
but to transform the elements of the stream, you can think of it as an analog of themap()
operation that is done not is the middle of the stream pipeline, but during the process of collecting the data.And if I understood your logic correctly, there's no need to apply
mapping()
here.