Search code examples
javastringsortingalphabetical-sort

Sorting a String by its 6 first characters


I have IDs with the following format : XXXXXXYYY00000

What I am trying to do is to get a single string organised alphabetically by the 6 first characters (the 6 x's (they can be any character)) with each new ID separated by a new line character

For example :

AOPSIKPMI23495 would go before BWLMBEPMI00001

What I have so far is :

String = String + this.ID + "\n";

And I have no idea how to approach my problem in order to solve it.

My question is the following : How do I organise my IDs alphabetically, only by its first 6 characters (meaning if there's a tie with the 6 first characters, it still shouldn't resolve it with the next 3 characters) and still keeping my String ?


Solution

  • you can sort the list by the first 6 characters and then use Collectors.joining to separate each string with a "\n" delimiter.

    String result = myList.stream().sorted(Comparator.comparing(e -> e.substring(0,6)))
                                   .collect(Collectors.joining("\n"));