2

I have a json as below and a similar classes respect to it MyClient:

[
    {
        "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 receives the uuid and it returns id.

Fr example findClientId("cf89cbc5-0886-48cc-81e7-ca6123bc4967") and then it returns 2:

Here is what i have tried:

  public static void findClientId(String partnerId, MyClient[] allMyClients) {
    Stream.of(allMyClients)
        .map(MyClient::getPartners)
        .forEach(Partner::getPartnerId)
        .filter(
            partner ->partner.id.equals(partnerId)))
    .map(MyClient::getId);
  }

But it complains Non-static method cannot be referenced from a static context in the line .forEach(Partner::getPartnerId)

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Jeff
  • 7,767
  • 28
  • 85
  • 138

1 Answers1

2

First, Stream.forEach is void. You can't invoke .filter or any other method after it. Beside that, .map(MyClient::getPartners) would make you lose MyClient information in the pipeline while it's MyClient.getId that you want. You'd have to use a nested stream to for filtering on partner list in each client.

Your code should be:

public static String findClientId(String partnerId, MyClient[] allMyClients) {
    return Stream.of(allMyClients)
            .filter(client -> client.getPartners()
                    .stream()
                    .anyMatch(partner -> partner.getPartnerId().equals(partnerId)))
            .map(MyClient::getId)
            .findAny()
            .orElse(null); // change to whatever is desired
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99