3

Other than to convert to UTF-8 bytes, or write a compare function that iterates and compares, is there some method I'm missing in JDK 1.6 that compares two strings in full Unicode codepoint order instead of in UCS-2 codepoint order?

I appreciate that this is not a hard thing to code. I was puzzled, however, that 1.6 has the various 'codepoint' APIs in java.lang.String as well as the Collation system, but apparently nothing to simply compare two strings without hiccuping on the surrogates.

For the benefit of a commenter, I have to feed some data to a tool that wants the strings in this order.

4
  • It already does that by default? Or do you actually want to take account with diacritics in the ordering? E.g. aa, , ab instead of (default) aa, ab, ? Otherwise I don't see any reason for this question :) Commented Jan 22, 2010 at 21:00
  • String.compareTo is at least in Sun's JVM 1.6.0_16 implemented as a comparison of the contained chars. This will not work with bmargulies requirement if the string contains surrogate pairs for characters outside the BMP. Commented Jan 22, 2010 at 21:43
  • Actually, this behaviour is described in the API documentation, so it's not an implementation detail of Sun's VM to base compareTo on the char values. Commented Jan 22, 2010 at 21:55
  • 1
    Is there now a solution for this in the current Java 1.8/1.9 API? Or maybe within a library? Commented Jun 3, 2018 at 9:56

2 Answers 2

1

AFAIk, the API has no such method, but it should be trivial to implement it yourself. Just out of curiosity: What do you need something like that for?

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

Comments

0

For the sake of completeness her my solution to the problem. Maybe there is a better solution:

   String sortedText = text
      .codePoints()
      .sorted()
      .mapToObj(i -> String.valueOf(Character.toChars(i)))
      .collect(Collectors.joining(""));

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.