I am trying to sort the JSONObject
array in Java . Can someone please tell me how can I sort based on locale
in Java just similar to JavaScript's localeCompare()
?
In JavaScript, we can do locale sort like below, arr.sort( ( a, b ) => a.data[ "nested-name" ].localeCompare(b.data[ "nested-name" ]) )
I want to do locale compared sorting in Java.
You can use a Collator
:
Collator collator = Collator.getInstance();
Arrays.sort(array, (JSONObject o1, JSONObject o2) ->
collator.compare(o1.get("data"), o2.get("data")));
Here's a complete example with a collator that uses the default locale to compare an array of JSON objects based on their data
property:
import org.json.JSONObject;
import java.text.Collator;
import java.util.Arrays;
public class LocaleCompareTest {
public static void main(String[] args) {
JSONObject a = new JSONObject();
a.put("data", "a");
JSONObject b = new JSONObject();
b.put("data", "b");
JSONObject[] array = new JSONObject[]{b, a};
Collator collator = Collator.getInstance();
Arrays.sort(array, (JSONObject o1, JSONObject o2) ->
collator.compare(o1.get("data"), o2.get("data")));
System.out.println(Arrays.toString(array));
}
}
This yields the following output:
[{"data":"a"}, {"data":"b"}]
See the Javadoc for more information on how to configure your collator for your desired locale and collation rules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.