-1

I have a data input file with a series of Strings. For example:

0001zz99ab9ssss
0002zz4p921ssss
0003zz123i5ssss
0004zzA9382ssss
0005zz4p921ssss

I want to sort these strings based off of the substring (6,11) in ascending order. So the output should be:

0003zz123i5ssss
0002zz4p921ssss
0005zz4p921ssss
0001zz99ab9ssss
0004zzA9382ssss

I'm also using ArrayLists if that helps.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
anon
  • 9
  • 2
  • 2
    Does this answer your question? [sorting strings in Java based on substrings](https://stackoverflow.com/questions/39444014/sorting-strings-in-java-based-on-substrings) – Amir Dora. Feb 13 '21 at 21:23
  • 1
    The question is closed for "needs more focus", and yet three people are able to understand it and provide answers? This is the usual "close it by any means necessary" welcome from SO. – user15187356 Feb 13 '21 at 23:19
  • I apologize for the SO community for such a "welcoming" behavior. Unfortunately some of us tend to exercise their right to close questions as soon as they’re given such opportunity. A sort of Stanford Experiment imho. The question was absolutely normal and within all SO standards. – andbi Feb 14 '21 at 03:05
  • @andbi I do not think so. I can see no effort in the question which should be be done before asking. For me it looks like *make my work for me* question – Jens Feb 14 '21 at 10:06

3 Answers3

1

Implement a comparator and use it in the sort.

class SubstringComparator implements Comparator<String> {
     public int compare(String s1, String s2) {
         return s1.substring(6,11).compareTo(s2.substring(6,11));
     }
}

and use it in the sort.

Collections.sort(myList, new SubstringComparator());
user15187356
  • 807
  • 3
  • 3
1

While other answers are correct, they do not optimise memory usage: for every comparison, you create two new strings, while there is an approach with no heap allocation happening at all in the comparator:

Comparator<String> comparator = (a, b) -> {
    for (int i = 6; i < 11; i++) {
        int cmp = Character.compare(a.charAt(i), b.charAt(i));
        if (cmp != 0) {
            return cmp;
        }
    }
                
    return 0;
};

P.S. This code doesn't consider the cases when there are strings shorter than 10 characters (same as others) - do not forget to account for them if they may be present in your input

Andrew Vershinin
  • 1,958
  • 11
  • 16
0

I suggest using a comperator in a stream.

List<String> values = List.of("0001zz99ab9ssss","0002zz4p921ssss", "0003zz123i5ssss", "0004zzA9382ssss", "0005zz4p921ssss");
List<String> result =  values.stream()
                                  .sorted(Comparator.comparing(o -> o.substring(6, 11)))
                                  .collect(Collectors.toList());
p.streef
  • 3,652
  • 3
  • 26
  • 50