जावा स्ट्रीम: json से आईडी कैसे खोजें? [डुप्लिकेट]

Oct 19 2020

मेरे पास एक जसन है जैसा कि नीचे है और एक समान वर्ग इसका सम्मान करता है 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"
            }
        ]
    }
]

मुझे एक विधि की आवश्यकता है जो यूआईडी प्राप्त करता है और यह आईडी देता है ।

Fr उदाहरण findClientId("cf89cbc5-0886-48cc-81e7-ca6123bc4967")और फिर यह लौटा 2:

यहाँ मैं कोशिश की है:

  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);
  }

लेकिन यह Non-static method cannot be referenced from a static contextलाइन में शिकायत करता है.forEach(Partner::getPartnerId)

जवाब

2 ernest_k Oct 20 2020 at 02:34

सबसे पहले, Stream.forEachशून्य है। आप .filterइसके बाद या किसी अन्य विधि को लागू नहीं कर सकते । इसके अलावा, जब आप चाहते हैं कि आप पाइपलाइन में जानकारी .map(MyClient::getPartners)खो देंगे । आपको प्रत्येक क्लाइंट में भागीदार सूची को फ़िल्टर करने के लिए नेस्टेड स्ट्रीम का उपयोग करना होगा।MyClientMyClient.getId

आपका कोड होना चाहिए:

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
}