JAVA对ArrayList排序
ava如何对ArrayList中对象按照该对象某属性排序
增加排序功能,打印时:输出学生对象的时候,需要先按照年龄排序,如果年龄相同,则按照姓名排序,如果姓名也相同,则按照学号排序。
- Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class ComparableTest {
- public static void main(String[] args) {
- Comparator<Student> comparator = new Comparator<Student>(){
- public int compare(Student s1, Student s2) {
- //先排年龄
- if(s1.age!=s2.age){
- return s1.age-s2.age;
- }
- else{
- //年龄相同则按姓名排序
- if(!s1.name.equals(s2.name)){
- return s1.name.compareTo(s2.name);
- }
- else{
- //姓名也相同则按学号排序
- return s1.id-s2.id;
- }
- }
- }
- };
- Student stu1 = new Student (1,"zhangsan","male",28,"cs");
- Student stu2 = new Student (2,"lisi","female",19,"cs");
- Student stu3 = new Student (3,"wangwu","male",22,"cs");
- Student stu4 = new Student (4,"zhaoliu","female",17,"cs");
- Student stu5 = new Student (5,"jiaoming","male",22,"cs");
- ArrayList<Student> List = new ArrayList<Student>();
- List.add(stu1);
- List.add(stu2);
- List.add(stu3);
- List.add(stu4);
- List.add(stu5);
- //这里就会自动根据规则进行排序
- Collections.sort(List,comparator);
- display(List);
- }
- static void display(ArrayList<Student> lst){
- for(Student s:lst)
- System.out.println(s);
- }
- }
- class Student{
- int age;
- int id;
- String gender;
- String name;
- String cs;
- Student(int id,String name,String gender,int age,String cs){
- this.age=age;
- this.name=name;
- this.gender=gender;
- this.id=id;
- this.cs=cs;
- }
- public String toString(){
- return id+" "+name+" "+gender+" "+age+" "+cs;
- }
- }
以一个point点类做例子:
- Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.util.*;
- public class Test {
- public static void main(String[] args){
- List<Point> points=new ArrayList<Point>();
- Point point1=new Point();
- point1.setX(1324);
- point1.setY(345);
- point1.setZ(436);
- points.add(point1);
- Point point2=new Point();
- point2.setX(23);
- point2.setY(8941.656);
- point2.setZ(431412);
- points.add(point2);
- Point point3=new Point();
- point3.setX(786584);
- point3.setY(23452);
- point3.setZ(43563);
- points.add(point3);
- //根据X排序
- Collections.sort(points,new SortByX());
- for(Point p:points){
- System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
- System.out.println();
- }
- //根据Y排序
- // Collections.sort(points,new SortByY());
- //
- // for(Point p:points){
- // System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
- // System.out.println();
- // }
- //
- // //根据Z排序
- // Collections.sort(points,new SortByZ());
- //
- // for(Point p:points){
- // System.out.print(p.getX()+"\t"+p.getY()+"\t"+p.getZ());
- // System.out.println();
- // }
- }
- }
- class Point{
- private double x;
- private double y;
- private double z;
- public double getX() {
- return x;
- }
- public void setX(double x) {
- this.x = x;
- }
- public double getY() {
- return y;
- }
- public void setY(double y) {
- this.y = y;
- }
- public double getZ() {
- return z;
- }
- public void setZ(double z) {
- this.z = z;
- }
- public Point(){}
- }
- //根据X排序
- class SortByX implements Comparator{
- public int compare(Object obj1,Object obj2){
- Point point1=(Point)obj1;
- Point point2=(Point)obj2;
- if(point1.getX()>point2.getX())
- return 1;
- else
- return 0;
- }
- }
- //根据Y排序
- class SortByY implements Comparator{
- public int compare(Object obj1,Object obj2){
- Point point1=(Point)obj1;
- Point point2=(Point)obj2;
- if(point1.getY()>point2.getY())
- return 1;
- else
- return 0;
- }
- }
- //根据Z排序
- class SortByZ implements Comparator{
- public int compare(Object obj1,Object obj2){
- Point point1=(Point)obj1;
- Point point2=(Point)obj2;
- if(point1.getZ()>point2.getZ())
- return 1;
- else
- return 0;
- }
- }
- Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->//一个POJO例子
- class User {
- String name;
- String age;
- public User(String name,String age){
- this.name=name;
- this.age=age;
- }
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- //具体的比较类,实现Comparator接口
- import java.util.Comparator;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Collections;
- public class ComparatorUser implements Comparator{
- public int compare(Object arg0, Object arg1) {
- User user0=(User)arg0;
- User user1=(User)arg1;
- //首先比较年龄,如果年龄相同,则比较名字
- int flag=user0.getAge().compareTo(user1.getAge());
- if(flag==0){
- return user0.getName().compareTo(user1.getName());
- }else{
- return flag;
- }
- }
- }
- //测试类
- public class SortTest {
- public static void main(String[] args){
- List userlist=new ArrayList();
- userlist.add(new User("dd","4"));
- userlist.add(new User("aa","1"));
- userlist.add(new User("ee","5"));
- userlist.add(new User("bb","2"));
- userlist.add(new User("ff","5"));
- userlist.add(new User("cc","3"));
- userlist.add(new User("gg","6"));
- ComparatorUser comparator=new ComparatorUser();
- Collections.sort(userlist, comparator);
- for (int i=0;i<userlist.size();i++){
- User user_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
代码:
- Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class Testa
- {
- public static void main(String[] args)
- {
- //传入参数为文件目录
- test("d:/a.txt");
- }
- public static void test(String filePath){
- BufferedReader br = null;
- try {
- br = new BufferedReader(new FileReader(filePath));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return;
- }
- String []columnName = {"Id", "Name", "Languages", "Math", "English"}; //列名
- int []courseIndexs = {2, 3, 4}; //课程对应的列
- int i,j,index;
- String line;
- List<Map<String, Object>> students = new ArrayList<Map<String, Object>>();
- //记录Id和总值,用于排序
- List<Map<String, Object>> sortList = new ArrayList<Map<String, Object>>();
- try {
- br.readLine(); //去掉第一行
- while((line = br.readLine()) != null){
- index = 0;
- String []se = line.split(" ");
- Map<String, Object> student = new HashMap<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++;
- }
- //计算平均值,总值
- double total = 0;
- for(j = 0; j < courseIndexs.length; j++){
- total += Double.parseDouble((String) student.get(columnName[courseIndexs[j]]));
- }
- double average = total / courseIndexs.length;
- //只取一位小数
- average = Math.round(average * 10)/10;
- student.put("Total", total);
- student.put("Average", average);
- Map<String, Object> sort = new HashMap<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 = new HashMap<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")));
- }
- //输出(写到原文件)
- //PrintWriter pw = new PrintWriter(new File(filePath));
- //输出(写到其他文件)
- PrintWriter pw = new PrintWriter(new File("D:/b.txt"));
- pw.println("Id\tName\tLan\tMath\tEnglish\tAverage\tTotal\tSort");
- int cIndex;
- 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 (IOException e) {
- e.printStackTrace();
- }
- }
- }
JAVA对ArrayList排序的更多相关文章
- java 使用 ArrayList 排序【包括数字和字符串】
1.数字排序 /** * 数字排序 */ @Test public void t2() { List<Integer> list = new ArrayList<>(); li ...
- Java ArrayList排序方法详解
由于其功能性和灵活性,ArrayList是 Java 集合框架中使用最为普遍的集合类之一.ArrayList 是一种 List 实现,它的内部用一个动态数组来存储元素,因此 ArrayList 能够在 ...
- 【BigData】Java基础_定义工具类,对ArrayList排序并且求最大值、最小值、平均值
需求描述 编写一个工具类,对ArrayList实现以下功能: ① 排序 ② 求最大值 ③ 求最小值 ④ 求平均值 需求实现 实现代码 package cn.test.logan.day04; impo ...
- java@ 利用ArrayList实现dijkstra算法以及topological 排序算法(java.util.ArrayList)
package dataStructure; import java.util.ArrayList; import java.util.LinkedList; import java.util.Que ...
- java List的排序
List自定义排序 1.第一种方法,就是list中对象实现Comparable接口,重写compareTo接口, 对排序的字段进行比较.2.第二种方法,就是在重载Collections.sort方法. ...
- Java的List排序
有时需要对List排序,这时可以利用Collections的sort()方法来排序,不用自己再去排序. package myTest; import java.util.ArrayList; impo ...
- ArrayList排序
今天发现,ArrayList 排序不满足期望. 起先,List是这样Before sort: [1, @I, am, Love, java, very, Much] 使用Collections.sor ...
- java 16-1 ArrayList的练习1
需求: ArrayList去除集合中字符串的重复值(去掉相同的字符串) 分析: 第一种做法:创建一个新的空集合: A:创建1个具有相同字符串的集合 B:创建1个空的集合 C:遍历第一个集合里面的元素 ...
- java中ArrayList 、LinkList区别
转自:http://blog.csdn.net/wuchuanpingstone/article/details/6678653 个人建议:以下这篇文章,是从例子说明的方式,解释ArrayList.L ...
随机推荐
- tomcat配置使用log4j管理日志
从tomcat官网下载和tomcat对应的tomcat-juli.jar和tomcat-juli-adapters.jar,从log4j官网下载log4j的jar包(我用的是log4j-1.2.17. ...
- MySQL表的创建与维护
一.导入测试数据 [root@server ~]# wget https://launchpadlibrarian.net/24493586/employees_db-full-1.0.6.tar.b ...
- 《精通并发与Netty》学习笔记(12 - 详解NIO (三) SocketChannel、Pipe)
一.SocketChannelJava NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel ...
- shell学习笔记1-文件安全与权限
1,创建文件的用户和他所属的组拥有该文件,文件的属主可以设定谁具有读.写.执行该文件的权限,根用户可以改变任何普通用户的设置. 2,一个文件一经创建,就具有三种访问权限:读(可以显示该文件的内容).写 ...
- C#实现工作日和休息日(包括法定节假日)的计算
转自:http://www.cnblogs.com/yuan-chong/p/HolidayHelper.html 一.开发背景: 最近在公司开发的系统中,需要计算工作日,就是给出一个采购周期(n天) ...
- Vue.js 关于双向绑定的一些实现细节
Vue.js 是采用 Object.defineProperty 的 getter 和 setter,并结合观察者模式来实现数据绑定的. 当把一个普通 Javascript 对象传给 Vue 实例来作 ...
- sqlite3数据库修复SQLite-database disk image is malformed
目录 sqlite3数据库修复SQLite-database disk image is malformed title: sqlite3数据库修复SQLite-database disk image ...
- UWP 保存音乐或视频缩略图图片到本地
开发项目时,有时需要将本地媒体文件的缩略图保存到本地,下面是源码. 需要打开Package.appxmanifest 功能 图片库 访问权限. <Page x:Class="SaveB ...
- vue-router 在微信浏览器中操作history URl未改变的解决方案
在PC端和手机浏览器中router.replace() or router.push()能够正常使用,页面的地址和页面都正常显示:但是在微信中,从/a页面通过router.push('/b')跳转到/ ...
- [转帖]Cookie与Passport安全
Cookie与Passport安全 https://www.cnblogs.com/xinzhao/p/6395153.html 感觉自己对网络安全性的理解还是不深入 不透彻. 对于web系统而言,由 ...