0

I have this function:

        playerList.forEach(pl ->{
            JSONObject player = (JSONObject) pl;
            System.out.println(player.get("UUID")+" : " + uuid+" :")

but there is an error on the line "return warps" that say "Unexpected return value". Why is this happening?

2
  • 1
    What do you expect return warps; to do within a forEach Consumer? Commented Mar 31, 2021 at 18:50
  • So, if I try to return a string that's work, but if i try to return a JSONArray it gives me this error. I just want to return a JsonArray Commented Mar 31, 2021 at 18:54

2 Answers 2

1

Like what am9417 mentioned, your return statement is inside the forEach scope which is a void function, hence the error you're getting.

Here are two options you can try and play around with:

  1. Using streams. Here I used filter to get the item/s which matches the uuid criteria(argument in your example method). And then findFirst at the end to always get the first occurrence assuming you're expecting 1 UUID match all the time.
// using findFirst returns an Optional type.
Optional<JSONObject> optionalPlayer = playerList
       .stream()
       .filter(pl -> {
           JSONObject player = (JSONObject) pl;
           System.out.println(player.get("UUID") + " : " + uuid + " :");
           return player.get("UUID").equals(uuid);
       }).findFirst();

if (optionalPlayer.isPresent()) {
   return (JSONArray) optionalPlayer.get().get("warps");
}
  1. Using a simple for loop:
JSONArray playerList = (JSONArray) obj;

for (Object pl: playerList) {
    JSONObject player = (JSONObject) pl;
    System.out.println(player.get("UUID") + " : " + uuid + " :");
    if (player.get("UUID").equals(uuid)) {
        return (JSONArray) player.get("warps");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are returning the warps inside an anonymous function (ForEach for playerList) so the signature for ForEach does not match, which gives the error.

You should use most likely filter and suitable terminator for your stream. Then just return the collected JSONArray from your getWarps method.

2 Comments

can you explain?(sorry but I'm new to java)
Looks like you're not comfortable with Java Streams, so rewrite your code, e.g. by using "ordinary" loops and get rid of the Stream (that is: the structure with playerList.ForEach ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.