Sorting standards with alphanumeric data (and special characters) based on case insensitivity in Java

I have a list of character sequences. I need to sort them in an order that seems natural. I am coding in Java. My initial thought was to use Collections.sort(). But I think this method follows the ASCII order, which separates lowercase and uppercase. This is not a natural flow.

Trying to define “natural sorting,” I did a quick search and found the NISO TR03-1999 standard, which seems to solve this problem.

So, I think I need a sorting method using the algorithm defined in this standard. Is there a function in Java for this? Or do I need to implement it myself?

Is there something I'm looking at here?

Has anyone had a similar problem in the past? How did you deal with this?

Here's an example of testing Collections.sort () code:

List<String> list = new ArrayList<String>();

list.add("z");
list.add("a");
list.add("Z");
list.add("A");
list.add("z 1");
list.add("a 1");
list.add("Z 1");
list.add("A 1");
list.add(" space");
list.add("!");
list.add(".");
list.add(";");
list.add("\\");
list.add("/");
list.add("+");
list.add("1");
list.add("2");
list.add("10");
list.add("1abc");
list.add("2abc");
list.add("10abc");

Collections.sort(list);

for (String string : list)
    System.out.println(string);
+4
source share
3 answers
+2
source

You can create your own comparator class that compares and ignores the case.

static class StringCompare implements Comparator<String> {               
  public int compare(String s1, String s2){
        return s1.toLowerCase().compareTo(s2.toLowerCase());
  }
}

And then use this to sort:

Collections.sort(list, new StringCompare());
+1
source

Use apache-common StringUtils in comparator implementation:

class StringCompare implements Comparator<String> {               
    public int compare(String s1, String s2){
        return StringUtils.stripAccents(s1.toLowerCase()).compareTo(StringUtils.stripAccents(s2.toLowerCase()));
   }
}
+1
source

Source: https://habr.com/ru/post/1598956/


All Articles