Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Java: What is Java's alternative to JavaScript's localeCompare()?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!