简体   繁体   中英

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.

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) .

我在这个网站上找到了一种不错的方法,基本上,您要在程序中添加的这一行是这里的: Collections.sort(myList, Comparator.comparing((String s) -> s.substring(3, 4)));

在jave 8中,您可以尝试以下代码

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM