英文:
Java8-Stream: no instance(s) of type variable(s)
问题
以下是翻译好的内容:
public List<String> getPartnersOfClient(String clientId, MyClient[] allMyClients) {
Stream<String> myClient =
Stream.of(allMyClients)
.filter(client -> client.getId() == Integer.valueOf(clientId))
.flatMap(client -> Arrays.stream(client.getPartners())
.map(partner -> partner.getId()))
.collect(Collectors.toList());
return myClient;
}
请注意,翻译中的代码可能需要根据实际情况进行适当的调整。如果有任何问题或需要进一步帮助,请随时提问。
英文:
I have a json as below:
[
{
"id": 2,
"partners": [
{
"configuration": {
"connect-fleet-sync": false
},
"id": "cf89cbc5-0886-48cc-81e7-ca6123bc4857"
},
{
"configuration": {
"connect-fleet-sync": false
},
"id": "cf89cbc5-0886-48cc-81e7-ca6123bc4967"
}
]
},
{
"id": 3,
"partners": [
{
"configuration": {
"connect-fleet-sync": false
},
"id": "c3354af5-16e3-4713-b1f5-a5369c0b13d6"
}
]
}
]
I need a method which i receive the id and it gives me ids of partners.
Fr example getPartnersOfClient(2)
and then i expect it returns:
["cf89cbc5-0886-48cc-81e7-ca6123bc4857","cf89cbc5-0886-48cc-81e7-ca6123bc4857"]
Here is what i have tried:
public List<String> getPartnersOfClient(String clientId, MyClient[] allMyClients) {
Stream<String> myClient =
Stream.of(allMyClients)
.filter(client -> client.getId() == Integer.valueOf(clientId))
.map(MyClient::getPartners)
.map(Partner::getPartnerId)
.collect(Collectors.toList());
return allPartners;
}
But, in the line .map(Partner::getPartnerId)
it complains with:
reason: no instance(s) of type variable(s) exist so that Partner[] conforms to Partner
Here is the picture of error:
答案1
得分: 1
看起来 getPartners()
返回的是 Partner[]
,而不是一个 Partner
,因此你不能在这些数组上使用 Partner::getPartnerId
。
你可以使用 flatMap
来获得所有单独的 Partner
实例的 Stream<Partner>
。
Stream<String> fdeClient =
Stream.of(allFdeClients)
.filter(client -> client.getId() == Integer.parseInt(clientId))
.flatMap(f -> Stream.of(f.getPartners()))
.map(Partner::getPartnerId)
.collect(Collectors.toList());
英文:
It looks like getPartners()
returns a Partner[]
, not a Partner
, so you can't apply Partner::getPartnerId
on these arrays.
You can use flatMap
to get a Stream<Partner>
of all the individual Partner
instances.
Stream<String> fdeClient =
Stream.of(allFdeClients)
.filter(client -> client.getId() == Integer.parseInt(clientId))
.flatMap(f -> Stream.of(f.getPartners()))
.map(Partner::getPartnerId)
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论