
com.enterprisemath.utils.PropertyStringComparator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of em-utils Show documentation
Show all versions of em-utils Show documentation
Collection of utility classes for large scale projects focusing on robust and testable code.
package com.enterprisemath.utils;
import java.util.Comparator;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Comparator for strings in the property files.
* For example strings like items[0].id or items[1].name and similar are good examples.
* Compare is aware of arrays so for example string like items[9] and items[10] gets ordered in the ascendant order.
*
* @author radek.hecl
*
*/
public class PropertyStringComparator implements Comparator {
/**
* Creates new instance.
*/
private PropertyStringComparator() {
}
@Override
public int compare(String o1, String o2) {
ValidationUtils.guardNotNull(o1, "o1 is null which is not supported");
ValidationUtils.guardNotNull(o2, "o2 is null which is not supported");
if (o1.equals(o2)) {
return 0;
}
String[] parts1 = o1.split("\\.");
String[] parts2 = o2.split("\\.");
int max = Math.min(parts1.length, parts2.length);
for (int i = 0; i < max; ++i) {
String part1 = parts1[i];
String part2 = parts2[i];
if (part1.equals(part2)) {
continue;
}
if (part1.matches("^.+\\[[0-9]+\\]$") && part2.matches("^.+\\[[0-9]+\\]$")) {
String[] pp1 = part1.split("[\\[\\]]", 3);
String[] pp2 = part2.split("[\\[\\]]", 3);
if (pp1[0].equals(pp2[0])) {
int index1 = Integer.valueOf(pp1[1]);
int index2 = Integer.valueOf(pp2[1]);
if (index1 == index2) {
continue;
}
else {
return index1 < index2 ? -1 : 1;
}
}
else {
return pp1[0].compareTo(pp2[0]) < 0 ? -1 : 1;
}
}
else {
return part1.compareTo(part2) < 0 ? -1 : 1;
}
}
return parts1.length < parts2.length ? -1 : 1;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
/**
* Creates new instance.
*
* @return created instance
*/
public static PropertyStringComparator create() {
return new PropertyStringComparator();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy