Convert Set to JSONArray in Java 8 Can this be optimized for Java 8 and can it be more efficient? I am using streams and lambdas.

public String LanguageString(Set&lt;Locale&gt; 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();
}
You should not catch exceptions and discard them silently. This code has no chance of throwing an exception, therefore you should just let the exception bubble up and let someone else catch it. If it should ever happen.
Your variable names don't express their intention. The word temp should not be used at all, you mix terminology between languages and locale. Sometimes you put the j at the beginning of the name, sometimes at the end; this is inconsistent.
Declare your variables as late as possible (json).
Declare your variables in the smallest possible scope (tempj).
Method names in Java start with a lowercase letter.
Don't declare throws Exception when your code doesn't actually do that.
It is unusual that the languages set actually contains null. So in general you should leave out the if (language != null) check.


After following all these hints, the code may look like this:

public String createLanguagesJson(Set&lt;Locale&gt; languages) {
    JSONArray array = new JSONArray();
    for (Locale language : languages) {
        array.put(new JSONObject()
                .put("lcode", language.toLanguageTag())
                .put("ldisplay", language.getDisplayName()));
    }

    return new JSONObject()
            .put("root", array)
            .toString();
}