`
aerchi
  • 浏览: 428370 次
  • 性别: Icon_minigender_1
  • 来自: 昆明
文章分类
社区版块
存档分类
最新评论

JAVA对ArrayList排序

 
阅读更多

以下前三个代码都是通过实现Comparable接口,或是实例化一个比较器,虽然重点部分重复了,也各有不同,还是都贴上吧。

http://zhidao.baidu.com/question/97784478

java如何对ArrayList中对象按照该对象某属性排序

增加排序功能,打印时:输出学生对象的时候,需要先按照年龄排序,如果年龄相同,则按照姓名排序,如果姓名也相同,则按照学号排序。

importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Comparator;

publicclassComparableTest{
publicstaticvoidmain(String[]args){
Comparator<Student>comparator=newComparator<Student>(){
publicintcompare(Students1,Students2){
//先排年龄
if(s1.age!=s2.age){
returns1.age-s2.age;
}
else{
//年龄相同则按姓名排序
if(!s1.name.equals(s2.name)){
returns1.name.compareTo(s2.name);
}
else{
//姓名也相同则按学号排序
returns1.id-s2.id;
}
}
}
};
Studentstu1=newStudent(1,"zhangsan","male",28,"cs");
Studentstu2=newStudent(2,"lisi","female",19,"cs");
Studentstu3=newStudent(3,"wangwu","male",22,"cs");
Studentstu4=newStudent(4,"zhaoliu","female",17,"cs");
Studentstu5=newStudent(5,"jiaoming","male",22,"cs");

ArrayList<Student>List=newArrayList<Student>();
List.add(stu1);
List.add(stu2);
List.add(stu3);
List.add(stu4);
List.add(stu5);
//这里就会自动根据规则进行排序
Collections.sort(List,comparator);
display(List);
}

staticvoiddisplay(ArrayList<Student>lst){
for(Students:lst)
System.out.println(s);
}
}

classStudent{
intage;
intid;
Stringgender;
Stringname;
Stringcs;
Student(intid,Stringname,Stringgender,intage,Stringcs){
this.age=age;
this.name=name;
this.gender=gender;
this.id=id;
this.cs=cs;
}
publicStringtoString(){
returnid+""+name+""+gender+""+age+""+cs;
}
}


http://ajava.org/code/Collections/14160.html

以一个point点类做例子:

importjava.util.*;

publicclassTest{

publicstaticvoidmain(String[]args){
List<Point>points=newArrayList<Point>();

Pointpoint1=newPoint();
point1.setX(1324);
point1.setY(345);
point1.setZ(436);
points.add(point1);

Pointpoint2=newPoint();
point2.setX(23);
point2.setY(8941.656);
point2.setZ(431412);
points.add(point2);

Pointpoint3=newPoint();
point3.setX(786584);
point3.setY(23452);
point3.setZ(43563);
points.add(point3);

//根据X排序
Collections.sort(points,newSortByX());

for(Pointp:points){
System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
System.out.println();
}

//根据Y排序
//Collections.sort(points,newSortByY());
//
//for(Pointp:points){
//System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
//System.out.println();
//}
//
////根据Z排序
//Collections.sort(points,newSortByZ());
//
//for(Pointp:points){
//System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
//System.out.println();
//}
}

}

classPoint{
privatedoublex;
privatedoubley;
privatedoublez;
publicdoublegetX(){
returnx;
}
publicvoidsetX(doublex){
this.x=x;
}
publicdoublegetY(){
returny;
}
publicvoidsetY(doubley){
this.y=y;
}
publicdoublegetZ(){
returnz;
}
publicvoidsetZ(doublez){
this.z=z;
}
publicPoint(){}
}

//根据X排序
classSortByXimplementsComparator{
publicintcompare(Objectobj1,Objectobj2){
Pointpoint1=(Point)obj1;
Pointpoint2=(Point)obj2;
if(point1.getX()>point2.getX())
return1;
else
return0;
}
}
//根据Y排序
classSortByYimplementsComparator{
publicintcompare(Objectobj1,Objectobj2){
Pointpoint1=(Point)obj1;
Pointpoint2=(Point)obj2;
if(point1.getY()>point2.getY())
return1;
else
return0;
}
}
//根据Z排序
classSortByZimplementsComparator{
publicintcompare(Objectobj1,Objectobj2){
Pointpoint1=(Point)obj1;
Pointpoint2=(Point)obj2;
if(point1.getZ()>point2.getZ())
return1;
else
return0;
}
}


http://www.blogjava.net/zygcs/archive/2008/01/17/176032.html

//一个POJO例子

classUser{
Stringname;
Stringage;

publicUser(Stringname,Stringage){
this.name=name;
this.age=age;
}
publicStringgetAge(){
returnage;
}
publicvoidsetAge(Stringage){
this.age=age;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
}


//具体的比较类,实现Comparator接口

importjava.util.Comparator;
importjava.util.List;
importjava.util.ArrayList;
importjava.util.Collections;

publicclassComparatorUserimplementsComparator{

publicintcompare(Objectarg0,Objectarg1){
Useruser0=(User)arg0;
Useruser1=(User)arg1;

//首先比较年龄,如果年龄相同,则比较名字

intflag=user0.getAge().compareTo(user1.getAge());
if(flag==0){
returnuser0.getName().compareTo(user1.getName());
}else{
returnflag;
}
}

}




//测试类
publicclassSortTest{


publicstaticvoidmain(String[]args){
Listuserlist=newArrayList();
userlist.add(newUser("dd","4"));
userlist.add(newUser("aa","1"));
userlist.add(newUser("ee","5"));
userlist.add(newUser("bb","2"));
userlist.add(newUser("ff","5"));
userlist.add(newUser("cc","3"));
userlist.add(newUser("gg","6"));

ComparatorUsercomparator=newComparatorUser();
Collections.sort(userlist,comparator);

for(inti=0;i<userlist.size();i++){
Useruser_temp=(User)userlist.get(i);
System.out.println(user_temp.getAge()+","+user_temp.getName());
}

}
}

//首先年龄排序,如果年龄相同,则按名字排序

结果:
1, aa
2, bb
3, cc
4, dd
5, ee //注意:同样是5岁的人,则比较名字(ee,ff),然后排序
5, ff
6, gg

http://zhidao.baidu.com/question/135304880.html?push=ql

最后这个没有用java的Comparable接口,自己写的排序函数。

要用JAVA写个东西读取TXT中的数据 且要计算出平均值和总值 最后还要按总值排序。 
TXT的文件如下:

学号 姓名 语文 数学 英语 平均值 总值 排序
1 李守东 83 73 75
2 徐贤坤 58 58 87
3 钱云宋 41 86 90
4 陈平 83 43 65
5 金荣权 93 88 63
6 陈如棉 99 93 43
7 章可可 98 62 72
8 陈伟奔 87 43 76
9 张如祥 69 58 78
10 丁尚游 80 56 57
11 林宏旦 91 90 76
12 曾上腾 100 96 54
13 谢作品 82 100 55
14 温从卫 73 46 101
15 李明察 81 41 75
16 彭鸿威 46 46 89
17 翁文秀 57 43 58
18 陈家伟 63 58 98
19 温正考 100 64 57
20 周文湘 50 50 79
21 吴杰 65 65 83
22 赖登城 60 79 53
23 聂树露 51 76 45
24 张雅琴 68 95 56
25 曾瑞约 88 63 58
26 王志强 96 79 78
27 徐贤所 66 46 74
28 陈祥枭 82 96 91
29 温婷婷 41 73 96
30 应孔余 66 81 71
31 宋成取 71 68 62
32 黄益省 65 56 43
33 陈思文 55 100 44
34 上官福新 64 62 70
35 钟国横 49 69 56
36 林型涨 78 73 50
代码:

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

publicclassTesta
{
publicstaticvoidmain(String[]args)
{
//传入参数为文件目录
test("d:/a.txt");
}

publicstaticvoidtest(StringfilePath){
BufferedReaderbr=null;
try{
br=newBufferedReader(newFileReader(filePath));
}catch(FileNotFoundExceptione){
e.printStackTrace();
return;
}

String[]columnName={"Id","Name","Languages","Math","English"};//列名
int[]courseIndexs={2,3,4};//课程对应的列
inti,j,index;
Stringline;
List<Map<String,Object>>students=newArrayList<Map<String,Object>>();
//记录Id和总值,用于排序
List<Map<String,Object>>sortList=newArrayList<Map<String,Object>>();
try{
br.readLine();//去掉第一行
while((line=br.readLine())!=null){
index=0;
String[]se=line.split("");
Map<String,Object>student=newHashMap<String,Object>();
for(i=0;i<se.length;i++){
if("".equals(se[i])){
continue;
}
if(index>=columnName.length){
continue;
}
student.put(columnName[index],se[i]);
index++;
}
//计算平均值,总值
doubletotal=0;
for(j=0;j<courseIndexs.length;j++){
total+=Double.parseDouble((String)student.get(columnName[courseIndexs[j]]));
}
doubleaverage=total/courseIndexs.length;
//只取一位小数
average=Math.round(average*10)/10;
student.put("Total",total);
student.put("Average",average);

Map<String,Object>sort=newHashMap<String,Object>();
sort.put("Id",student.get("Id"));
sort.put("Total",student.get("Total"));
sortList.add(sort);

students.add(student);
}
br.close();

//选择排序
for(i=0;i<sortList.size();i++){
for(j=i+1;j<sortList.size();j++){
if((Double)sortList.get(i).get("Total")<(Double)sortList.get(j).get("Total")){
Map<String,Object>temp=sortList.get(i);
sortList.set(i,sortList.get(j));
sortList.set(j,temp);
}
}
}
Map<Object,Integer>sortedId=newHashMap<Object,Integer>();
for(i=0;i<sortList.size();i++){
sortedId.put(sortList.get(i).get("Id"),i+1);
}

//设定序号
for(j=0;j<students.size();j++){
students.get(j).put("Order",sortedId.get(students.get(j).get("Id")));
}

//输出(写到原文件)
//PrintWriterpw=newPrintWriter(newFile(filePath));
//输出(写到其他文件)
PrintWriterpw=newPrintWriter(newFile("D:/b.txt"));

pw.println("Id\tName\tLan\tMath\tEnglish\tAverage\tTotal\tSort");
intcIndex;
for(i=0;i<students.size();i++){
Map<String,Object>st=students.get(i);
cIndex=0;
pw.println(st.get(columnName[cIndex++])+"\t"+st.get(columnName[cIndex++])
+"\t"+st.get(columnName[cIndex++])+"\t"+st.get(columnName[cIndex++])
+"\t"+st.get(columnName[cIndex++])
+"\t"+st.get("Total")
+"\t"+st.get("Average")
+"\t"+st.get("Order"));
}
pw.flush();
pw.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics