Home > Blockchain >  How to sort by first few letters of string?
How to sort by first few letters of string?

Time:02-11

For example, if I have an array of strings {"Bob", "Bom", "Ash", "Ben"}, how do I sort it first by first letter (ASCII value), then by second letter, and so on without losing the previous sorted order? so after sorting it would become {"Ash", "Ben", "Bob", "Bom"}?

CodePudding user response:

You can use Arrays methods in util package

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      String[] ar = {"Bob", "Bom", "Ash", "Ben"};
      Arrays.sort(ar);
      System.out.println(Arrays.toString(ar));  
    }
}

CodePudding user response:

Pretty straight-forward - use custom Comparator that takes only first N letters (s.substring(0, N)):

String[] source = {"Bob", "Ben", "Bom", "Ash"};
int N = 2; // sort by first 2 chars

String[] result = Arrays.stream(source)
        .sorted(Comparator.comparing(s -> s.substring(0, N)))
        .toArray(String[]::new);

CodePudding user response:

Other option:

String[] names = {"Bob", "Bom", "Ash", "Ben"};
System.out.println(new TreeSet(Arrays.asList(names)));
  • Related