Java字符串排序的幾種實現(xiàn)方式
更新時間:2023年07月21日 10:17:56 作者:是小浩呀~
這篇文章主要給大家介紹了關于Java字符串排序的幾種實現(xiàn)方式, 使用Java平臺進行字符串排序被認為是一件簡單的工作,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
創(chuàng)建實體類(此處引入了lombok)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test{
private int Id;
private String TestNo;
}一、使用List集合中自帶的sort方法(字符串的位數(shù)保持一致,不一致的情況可以在左邊補0,也可以使用String.format()方法補全)
1、在對象排序中使用
public static void main(String[] args) {
List<Test> testList= new ArrayList<>();
testList.add(1,"22");
testList.add(2,"11");
testList.add(3,"44");
testList.add(4,"33");
list.sort((a,b)->a.getTestNo().compareTo(b.getTestNo()));
}2、在字符串排序中使用
public static void main(String[] args) {
List<String> testList= new ArrayList<>();
testList.add("22");
testList.add("11");
testList.add("44");
testList.add("33");
list.sort(String::compareTo);
}二、使用Stream流(字符串的位數(shù)保持一致,不一致的情況可以在左邊補0,也可以使用String.format()方法補全)
1、在對象排序中使用
public static void main(String[] args) {
List<Test> testList= new ArrayList<>();
testList.add(1,"22");
testList.add(2,"11");
testList.add(3,"44");
testList.add(4,"33");
List<Test> sortList = testList.stream().sorted(Comparator.comparing(Test::getTestNo).collect(Collectors.toList());
}2、在字符串排序中使用
public static void main(String[] args) {
List<String> testList= new ArrayList<>();
testList.add("22");
testList.add("11");
testList.add("44");
testList.add("33");
List<String> collect = testList.stream().sorted(Comparator.comparing(Objects::toString)).collect(Collectors.toList());
}三、使用基數(shù)排序(此處僅展示對字符串進行排序,不需要補全位數(shù))
class Quick3string{
//三向字符串快速排序
private static int charAt(String s, int d) {
if(d < s.length()) {
return s.charAt(d);
}
return -1;
}
public static void sort(String[] a) {
sort(a, 0, a.length - 1, 0);
}
private static void sort(String[] a, int lo, int hi, int d) {
if(hi <= lo) {
return;
}
int lt = lo, gt = hi, i = lo + 1;
int v = charAt(a[lo], d);
while(i <= gt) {
int t = charAt(a[i], d);
if(t < v) {
exch(a, lt++, i++);
}else if(t > v) {
exch(a, i, gt--);
}else {
i++;
}
}
//a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi]
sort(a, lo, lt - 1, d);
if(v >= 0) {
sort(a, lt, gt, d + 1);
}
sort(a, gt + 1, hi, d);
}
private static void exch(String[] a, int i, int j) {
String t = new String(a[i]);
a[i] = a[j];
a[j] = t;
}
public static void main(String[] args) {
String[] a = {"48328458C70490693231303331361020", "48326E48E1136A9E3139313131301020", "48326E48E1176F8A3139313131311020", "48326E48E12474713139313131311020"};
Quick3string.sort(a);
System.out.println(Arrays.toString(a));
}
}總結
到此這篇關于Java字符串排序的幾種實現(xiàn)方式的文章就介紹到這了,更多相關Java字符串排序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn)方法
這篇文章主要介紹了Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn),需要的朋友可以參考下2018-02-02
SpringBoot 如何使用RestTemplate發(fā)送Post請求
這篇文章主要介紹了SpringBoot 如何使用RestTemplate發(fā)送Post請求的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Redis 訂閱發(fā)布_Jedis實現(xiàn)方法
下面小編就為大家?guī)硪黄猂edis 訂閱發(fā)布_Jedis實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

