Class AlphaNumericComparator

java.lang.Object
journeymap.api.v2.common.util.AlphaNumericComparator
All Implemented Interfaces:
Comparator<String>

public class AlphaNumericComparator extends Object implements Comparator<String>

An alphanumeric comparator for comparing strings in a human readable format. It uses a combination numeric and alphabetic comparisons to compare two strings. This class uses standard Java classes, independent of 3rd party libraries.

For given list of strings:

file-01.doc
file-2.doc
file-03.doc
The regular lexicographical sort e.g. Collections.sort(java.util.List) will result in a sorted list of:
file-01.doc
file-03.doc
file-2.doc
But using this class, the result will be a more human readable and organizable sorted list of:
file-01.doc
file-2.doc
file-03.doc

Additionally this comparator uses Collator class to correctly sort strings containing special Unicode characters such as Umlauts and other similar letters of alphabet in different languages, such as: å, è, ü, ö, ø, or ý.

  • Constructor Details

    • AlphaNumericComparator

      public AlphaNumericComparator()
      Default constructor, uses the default Locale and default collator strength.
    • AlphaNumericComparator

      public AlphaNumericComparator(Locale locale)
      Constructor using the provided Locale and default collator strength.
      Parameters:
      locale - Desired Locale
    • AlphaNumericComparator

      public AlphaNumericComparator(Locale locale, int strength)
      Constructor with given Locale and collator strength value.
      Parameters:
      locale - Desired Locale
      strength - Collator strength value, any of: Collator.PRIMARY, Collator.SECONDARY, Collator.TERTIARY, or Collator.IDENTICAL
      See Also:
  • Method Details

    • compare

      public int compare(String s1, String s2)
      Compares two given String parameters. Both string parameters will be trimmed before comparison.

      If either parameter is null or empty after trim:

      • -1 when only the first parameter is null/empty,
      • 1 when only the second parameter is null/empty,
      • 0 when both are null/empty.
      Specified by:
      compare in interface Comparator<String>