集合类重写排序的方法
来源:互联网 发布:淘宝 举证有效规则 编辑:程序博客网 时间:2024/06/08 08:40
好了先贴下代码。首先建立实体类。point如下图
public class Point implements Serializable{
private String x;
private String y;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
public Point(String x, String y) {
super();
this.x = x;
this.y = y;
}
public Point() {
super();
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
有实体类之后。我们重写实体类Points按照我们的要求排序。我们先手动赋值先。
建立新的比较测试类使用工具Collections重写Comparator的比较方法
public class TestComparator {
public static void main(String args[]){
List<Point> points = new ArrayList<Point>();
points.add(new Point("第一条","a"));
points.add(new Point("第一条","abc"));
points.add(new Point("第二条","abc"));
points.add(new Point("第二条","ab"));
points.add(new Point("第三条","a"));
points.add(new Point("第三条","abc"));
for(Point p:points){
System.out.println(p);
}
List<Point> tempPoints = new ArrayList<Point>();//临时的数组
List<Point> newPoints = new ArrayList<Point>();//新的点击数组
String str = "";//定义开始比较的字符串
for(int i=0;i<points.size();i++){
if(!str.equals(points.get(i).getX())){
tempPoints.clear();//先清空临时比较的数据
str = points.get(i).getX();
for(int j=i;j<points.size();j++){
if(str.equals(points.get(j).getX())){
tempPoints.add(points.get(j));//放入数组中
}else{
break;
}
}
Collections.sort(tempPoints, new Comparator<Point>(){
public int compare(Point p1, Point p2) {
return p1.getY().length()-p2.getY().length();
}
});
newPoints.addAll(tempPoints);
}
}
for(Point p:newPoints){
System.out.println(p);
}
}
}
好了打印结果如下图所示。我们可以看到x相同的情况下,y按照长度做了升序排序了
Point [x=第一条, y=a]
Point [x=第一条, y=abc]
Point [x=第二条, y=abc]
Point [x=第二条, y=ab]
Point [x=第三条, y=a]
Point [x=第三条, y=abc]
Point [x=第一条, y=a]
Point [x=第一条, y=abc]
Point [x=第二条, y=ab]
Point [x=第二条, y=abc]
Point [x=第三条, y=a]
Point [x=第三条, y=abc]
- 集合类重写排序的方法
- 重写对象的hashCode()方法来对无序集合排序
- java 重写compareTo方法实现类排序
- C#中包含子类集合的类的Equals方法重写
- 重写集合中的某些方法
- 类的高级运用、异常、集合、文件读写、序列化、重写equals和hashCode方法实例
- 集合中存储时的对象重写比较方法
- 重写父类的方法
- 重写父类的方法
- 重写父类的方法
- 重写类的equals方法
- 重写父类的方法
- 重写父类的方法
- Swift基础语法: 30 - Swift的基类, 子类, 重写, 重写方法, 重写属性, 防止重写
- 对象的比较,排序,重写equals(),compareTo(),hashCode()方法
- 重写Arrays中的sort方法,实现数组的降序排序
- 最新版NGUI3.8.1之UIGrid的重写排序方法,
- 重写 Collections.sort 的 compare 方法自定义排序 例子
- Linux下which、whereis、locate、find 命令的区别
- BigDecimal类型比较大小
- BZOJ 1294 [SCOI2009]围豆豆Bean
- 低层次特征提取-------边缘检测
- split("\\s+") 和 split(" +") 有什么区别?
- 集合类重写排序的方法
- [AS2.2]Android 5.0新控件记录
- (最新)IIS Express发布网站,实现IP,域名访问站点
- 开发中遇见不懂的问题的解决方式
- container_of分析
- 解决ubuntu搜狗输入法,只有文本框且显示英文,打不出中文
- iOS UIView的属性
- 07.Java序列化与反序列化
- Basic Introduction of Multi-label Learning