Allan Tanaka
Allan Tanaka

Reputation: 307

Sorting string based on substring

I have list of strings like this

B2B16, A1B01, S1B32, A1B23, B1B44

I want to sort the order of string based on the substring(3,4) of each 5 string. I want to sort the string based on substring (3,4) that has 1,0,2,3,4 starting from small to big.

Expected result:

A1B01, B2B16, A1B23, S1B32, B1B44

I tried this:

myList.sort(Comparator.comparing(ssss -> ssss.substring(3, 4)).thenComparing(ssss -> ssss.subtring(3, 4), Comparator.reverseOrder()));

But it doesn't work.

Upvotes: 0

Views: 948

Answers (3)

Zilong Wang
Zilong Wang

Reputation: 584

In jave 8, you can try this code

list.sort((a,b) -> a.substring(3,4).compareTo(b.substring(3,4)));

Upvotes: 0

Henrique Sabino
Henrique Sabino

Reputation: 545

I found a nice way to do it in this site, basically the line that you want to add in your program is this one here: Collections.sort(myList, Comparator.comparing((String s) -> s.substring(3, 4)));

Upvotes: 1

Robert Kock
Robert Kock

Reputation: 6008

I'm a bit old fashioned and not used to Java8, but I would resolve this as follows:

class MyComparator implements Comparator<String>
{
  @Override
  public int compare(String s1,
                     String s2)
  {
    return (s1.substring(3, 5).compareTo(s2.substring(3, 5)));
  }
}

myList.sort(new MyComparator());

Since all strings have a length of 5, you might also use substring(3) instead of substring(3, 5).

Upvotes: 3

Related Questions