1

Following is my code can it be optimized for java 8 and can it be more efficient?

public String LanguageString(Set<Locale> languageSet) throws Exception {
JSONObject json = new JSONObject();
JSONObject tempj = new JSONObject();
JSONArray jArr = new JSONArray();
try {
  for (Locale locale : languageSet) {
    if (locale != null) {
      tempj = new JSONObject();
      tempj.put("lcode", locale.toLanguageTag());
      tempj.put("ldisplay", locale.getDisplayName());
      jArr.put(tempj);
    }
  }
  json.put("root", jArr);
} catch (JSONException e) {
  //
}
return json.toString();
}
4
  • Seems pretty fine to me, don't think you need to do more. Commented Jul 29, 2017 at 4:48
  • 1
    for code optimization/ review use code review --> (codereview.stackexchange.com) Commented Jul 29, 2017 at 4:48
  • Do you currently have a performance problem with it? If not, why bother? Commented Jul 29, 2017 at 5:39
  • if you declare a Language class with lcode & ldisplay properties to wrap a Locale, you'll found that is easy to convert to JSONArray. Commented Jul 29, 2017 at 13:15

1 Answer 1

2

If you want to use Java 8 and Stream API you can use stream, map and reduce to create your final JSONObject, e.g.

public static String languageStringUsingStream(Set<Locale> locales) {
    return new JSONObject()
            .put("root", locales.stream()
                    .map(locale -> new JSONObject()
                            .put("lcode", locale.toLanguageTag())
                            .put("ldisplay", locale.getDisplayName(Locale.ENGLISH))
                    )
                    .reduce(new JSONArray(), JSONArray::put, (a, b) -> a))
            .toString();
}

Here you can find a complete example:

https://gist.github.com/wololock/27bd296fc894f6f4594f997057218fb3

Sign up to request clarification or add additional context in comments.

Comments

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.