目录
  • 创建实体类(此处引入了lombok)
  • 一、使用List集合中自带的sort方法(字符串的位数保持一致,不一致的情况可以在左边补0,也可以使用String.format()方法补全)
    • 1、在对象排序中使用
    • 2、在字符串排序中使用
  • 二、使用Stream流(字符串的位数保持一致,不一致的情况可以在左边补0,也可以使用String.format()方法补全)
    • 1、在对象排序中使用
    • 2、在字符串排序中使用
  • 三、使用基数排序(此处仅展示对字符串进行排序,不需要补全位数)
    • 总结

      创建实体类(此处引入了lombok)

      @Data @AllArgsConstructor @NoArgsConstructor public class Test{ private int Id; private String TestNo; }

      一、使用List集合中自带的sort方法(字符串的位数保持一致,不一致的情况可以在左边补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流(字符串的位数保持一致,不一致的情况可以在左边补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()); }

      三、使用基数排序(此处仅展示对字符串进行排序,不需要补全位数)

      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 = {"C0", "48326E48E1136A9E01020", "48326E48E1176F8A11020", "48326E48E0"}; Quick3string.sort(a); System.out.println(Arrays.toString(a)); } }

      总结

      到此这篇关于Java字符串排序的几种实现方式的文章就介绍到这了,更多相关Java字符串排序内容请搜索本网站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本网站!

      您可能感兴趣的文章:

      • Java实现对字符串中的数值进行排序操作示例
      • java字符串数组进行大小排序的简单实现