001
014
015 package com.liferay.portal.kernel.util;
016
017 import java.io.Serializable;
018
019 import java.util.Comparator;
020
021
024 public class NumericalStringComparator
025 implements Comparator<String>, Serializable {
026
027 public NumericalStringComparator() {
028 this(true, false);
029 }
030
031 public NumericalStringComparator(boolean ascending, boolean caseSensitive) {
032 _ascending = ascending;
033 _caseSensitive = caseSensitive;
034 }
035
036 @Override
037 public int compare(String s1, String s2) {
038 if (s1 == null) {
039 s1 = StringPool.BLANK;
040 }
041
042 if (s2 == null) {
043 s2 = StringPool.BLANK;
044 }
045
046 int startsWithWeight = StringUtil.startsWithWeight(s1, s2);
047
048 boolean lastMatchingCharIsDigit = false;
049
050 if ((startsWithWeight > 0) &&
051 Validator.isDigit(s1.charAt(startsWithWeight - 1))) {
052
053 lastMatchingCharIsDigit = true;
054 }
055
056 s1 = s1.substring(startsWithWeight);
057 s2 = s2.substring(startsWithWeight);
058
059 String leadingDigits1 = StringUtil.extractLeadingDigits(s1);
060 String leadingDigits2 = StringUtil.extractLeadingDigits(s2);
061
062 int value = 0;
063
064 if ((lastMatchingCharIsDigit &&
065 (Validator.isNotNull(leadingDigits1) ||
066 Validator.isNotNull(leadingDigits2))) ||
067 (Validator.isNotNull(leadingDigits1) &&
068 Validator.isNotNull(leadingDigits2))) {
069
070 if (leadingDigits1.length() != leadingDigits2.length()) {
071 value = leadingDigits1.length() - leadingDigits2.length();
072 }
073 else {
074 int i1 = GetterUtil.getInteger(leadingDigits1);
075 int i2 = GetterUtil.getInteger(leadingDigits2);
076
077 value = i1 - i2;
078 }
079 }
080 else {
081 if (_caseSensitive) {
082 value = s1.compareTo(s2);
083 }
084 else {
085 value = s1.compareToIgnoreCase(s2);
086 }
087 }
088
089 if (_ascending) {
090 return value;
091 }
092 else {
093 return -value;
094 }
095 }
096
097 private boolean _ascending;
098 private boolean _caseSensitive;
099
100 }