基于ArrayList的对象多属性值排序

问题描述: 有对象Student具有学号、姓名两个属性,请用两个List对一组student对象进行排序,要求首先按照姓名排序,然后按照学号排序。

以下只是部分代码:

//按照名字排序
	public int compare(Student o1, Student o2) {
	    String name1 = o1.getStuName();
	    String name2 = o2.getStuName();
		return name1.compareTo(name2);//按照stuName的字母顺序排序。
	}


	public int compare(Student o1, Student o2) {
		
		int stuno1 = o1.getStuNo();
		int stuno2 = o2.getStuNo();
		
		int comparedResult = Collator.getInstance(Locale.CHINESE).compare(o1.getStuName(),o2.getStuName());
		if(comparedResult == 0 ){ //这里表示比较的两条记录的stuName相同。
		  if(stuno1>stuno2)//这里控制stuno是按升序还是降序。
		     return 1;//这里控制stuname是按升序还是降序。
		}
		return 0;
	}


输出结果:
排序前=======================================
stuNo:1,stuName:zhangsan
stuNo:6,stuName:liwen
stuNo:27,stuName:bandong
stuNo:19,stuName:kuge
stuNo:28,stuName:bandong
stuNo:3,stuName:xiezhonghua
stuNo:16,stuName:bandong
stuNo:12,stuName:sbf
排序中=======================================
stuNo:27,stuName:bandong
stuNo:28,stuName:bandong
stuNo:16,stuName:bandong
stuNo:19,stuName:kuge
stuNo:6,stuName:liwen
stuNo:12,stuName:sbf
stuNo:3,stuName:xiezhonghua
stuNo:1,stuName:zhangsan
排序后=======================================
stuNo:16,stuName:bandong
stuNo:27,stuName:bandong
stuNo:28,stuName:bandong
stuNo:19,stuName:kuge
stuNo:6,stuName:liwen
stuNo:12,stuName:sbf
stuNo:3,stuName:xiezhonghua
stuNo:1,stuName:zhangsan


详情请见附件。

你可能感兴趣的:(对象排序,ArrayList,Java面试)