1

A sample dataset would be:

ArrayList<String> a = new ArrayList<String>();
    a.add("5");
    a.add("10.5a");
    a.add("4");
    a.add("4c");
    a.add("4a");
    a.add("10.6a");
    a.add("3");

I'm looking for the output to be in the format of [3, 4, 4a, 4c, 5, 10.5a, 10.6a].

Java's sorting function (Collections.sort(a);) sorts the data set to [10.5a, 10.6a, 3, 4, 4a, 4c, 5].

So, I need a way to split the value of the number from the letter, and sort first by number(4 before 10) then by letter with a number coming before a number-letter (4 before 4a).

The main way this is different from other questions on stackoverflow is that there is no separator between the numeric and alphabetic characters- the strings cannot be split at a specific character.

The Alphanum Algorithm by Dave Koelle returns [3, 4, 4a, 4c, 5, 10.6a, 10a, 10b]- the 10.6a should come after 10a.

Solved

In the first few lines, change the first int from 48 to 46, which accepts the "-" and "." characters as digits when separating the numbers from letters. It also makes it so numbers can now have decimals and be negative with the caveat that if your data uses .'s or -'s as non-numerical characters it will mess up the results.

public class AlphanumComparator implements Comparator<String>
{
    private final boolean isDigit(char ch)
    {
        return ch >= 46 && ch <= 57;
scottyah
  • 23
  • 5

0 Answers0