Java 8 java 8-如何在stream.groupingBy中使用当前项
我有字符串列表作为输入,函数接收字符串作为参数并返回对象列表。我想把它包装在map中,其中key-current字符串来自list,而对象列表作为value-result函数Java 8 java 8-如何在stream.groupingBy中使用当前项,java-8,java-stream,grouping,Java 8,Java Stream,Grouping,我有字符串列表作为输入,函数接收字符串作为参数并返回对象列表。我想把它包装在map中,其中key-current字符串来自list,而对象列表作为value-result函数 List<String> keys = List.of("one", "two", "three"); public List<Entity> someFunction(String param) throws IOException; //how to put it into map? pri
List<String> keys = List.of("one", "two", "three");
public List<Entity> someFunction(String param) throws IOException;
//how to put it into map?
private Mapt<String, List<Entity>> getEntities() {
Map<String, List<Entity>> map = keys.stream()
.collect(Collectors.groupingBy(Function.identity(),
client.someFunction(?)));//how to pass current item to "someFunction"? and probably whap the exception
return map;
}
List key=List.of(“一”、“二”、“三”);
公共列表someFunction(字符串参数)抛出IOException;
//如何把它放到地图上?
私有映射getEntities(){
Map Map=keys.stream()
.collect(收集器.groupingBy(Function.identity()),
client.someFunction(?);//如何将当前项传递给“someFunction”?并且可能会处理异常
返回图;
}
收集器。groupingBy
似乎不是合适的收集器,因为您似乎没有分组,您只是将一个值映射到输入列表的每个键
使用toMap
:
private Map<String, List<Entity>> getEntities() {
return
keys.stream()
.collect(Collectors.toMap(Function.identity(),
k -> client.someFunction(k)));
}
私有映射getEntities(){
返回
keys.stream()
.collect(Collectors.toMap(Function.identity()),
k->client.someFunction(k));
}
I get编译器错误:someFunction(java.lang.String)无法应用于Do注意:someFunction(String param)抛出IOException
。正因为如此,即使在使用toMap
进行收集时,流的使用也不会像它看起来那样有效。这就是我所寻找的。我将用捕获IOException包装对本地方法的函数调用