Compare strings by natural order but ignoring string's prefix

Viewed 145

I am struggling to sort a stream of strings (or list, if you prefer) in natural order ignoring a prefix. The prefix begins always with let and could be followed by any numbers (example, let12 or let3021)

Sample input:

let3 art zero
let2 own kit dig
let1 art can

Sample desired output:

let1 art can
let3 art zero
let2 own kit dig

So a simple idea that I have tried is to do the following:

list.stream().sorted();

But the numbers get in the way, producing the following output:

let1 art can
let2 own kit dig
let3 art zero

How can achieve this result in a simple way? The ideal solution would be a Comparator, or anything that I can use in a stream flow.

Note: my attempt to use the Comparator failed due the fact that the prefix could be of any length.

Thank you for your time.

1 Answers

You're answering your own question: With a comparator.

Comparator<String> marcosPrefixIgnoringComparison =
    (a, b) -> a.substring(4).compareTo(b.substring(4));

That's assuming that the prefix is defined as 'the first 4 characters'. If it's more 'The string let, and then any number of digits', you'd have to do something else. Possibly regexes:

Comparator<String> marcosPrefixIgnoringComparison =
    (a, b) -> a.replaceFirst("^let\\d+\\s+", "").compareTo(
      b.replaceFirst("^let\\d+\\s+", ""));

your question is not particularly clear about what 'prefix' means, here.

Related