使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
来源:互联网 发布:布谷鸟算法 编辑:程序博客网 时间:2024/04/27 19:58
概要
本文章,讲解Collections.sort给List<String>
排序的一种情况:
List<String>
里的内容是整数
环境
- eclipse+JDK1.6
情景:
- 1
- 2
需求:
/**
* @date 2017-07-12
* @author LTF
* 把数组排成最小的数
* 题目描述
* 输入一个List集合,给集合里的数据排序,按照正序或倒序打印出集合里的所有数据。
* 例如输入集合[15,123,10,9,3]
* 正序打印 :3,9,10,15,123
* 倒序打印 :123,15,10,9,3
* 思路
* 通过Collection.sort()方法中的自定义比较器实现。若num1>num2,则说明num1满足要求。
*/
常规的排序方式:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
输出:
- 1
- 2
- 3
- 4
- 5
总结:输出的结果不是我们想要的,默认排序的是按照首字符的大小排序
自定义的排序方式:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
输出:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
总结:输出的结果是我们想要的结果
总结:
使用Collections.sort(List<T>,Comparator<T>)
,可以做到给特殊的需求排序。首先我们需要实现Comparator接口,重写public int compare(Object o1, Object o2) 方法。上述的案例里,T是String,我们在获取数据时,就能直接得到String数据。
已知List<String>
里的内容是整数的情况下,我们把数据转化为整数类型,然后用整数去比较,最后得出排序结果。
Created by 刘天方
阅读全文
0 0
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序(一)
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- 使用Collections.sort(List<T>,Comparator<? super T>)给List<String>排序
- Collections.sort(List<T> list, Comparator<? super T> c) 源代码分析
- sort(List<T> list, Comparator<? super T> c) 根据比较器产生的顺序排序
- android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)
- android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)
- 【Java】如何给List集合排序Collections.sort(list,new Comparator<Entity>)
- C# List<T>.Sort排序
- 剑指Offer——巧妙使用sort(List<T>,Comparator<? super T>)比较器
- collections.sort(list, comparator) 详解
- 通过Collections.sort 给 List 排序
- list的排序Comparator的compare(T lhs, T rhs)
- Java.util.Collections.sort(List l) 排序 [implements Comparator]
- Java利用Comparator与Collections.sort对List排序
- Java利用Comparator与Collections.sort对List排序
- java利用Comparator与Collections.sort对List排序
- PrintWriter 返回前端中文乱码
- 【云隐】windows下编译及使用libevent
- CSS3瀑布流
- Docker获取镜像报错 docker: Error response from daemon: unauthorized: incorrect username or password.
- HashMap源码分析
- 使用Collections.sort(List<T>,Comparator<T>)给List<String>排序(一)
- Spring Boot Jar 做为Linux服务启动项
- DataTables 详细设置(1)
- 计算机编程的经典书籍(强烈推荐)
- android中finish()与system.exit(0)的区别
- c++小技巧
- 大道至简,职场上做人做事做管理
- VK11 VK12 保存增强
- Joda-Time的使用