1: 使用Collections.sort排序 import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test2 { public static void main(String[] arg) { List
list = new ArrayList
(); list.add(new Student(2, "张三 ")); list.add(new Student(1, "李四 ")); list.add(new Student(4, "王二 ")); list.add(new Student(3, "赵五 ")); // Comparator
comparator = getComparator( "id "); Comparator
comparator = getComparator( "name "); Collections.sort(list, comparator); // 输出 for(Student stu : list) { System.out.println(stu.getId() + " --> " + stu.getName()); } } private static Comparator
getComparator(String fieldName) { if(fieldName.equalsIgnoreCase( "id ")) { return new StudentIdComparator
(); } if(fieldName.equalsIgnoreCase( "name ")) { return new StudentNameComparator
(); } return null; } } class Student { private int id; private String name;
} /** * 按照学生的 id 号大小升序排序 */ class StudentIdComparator
implements Comparator
{ public int compare(Student o1, Student o2) { return o1.getId() - o2.getId(); } } /** * 按照学生的 name 的 GB2312 编码排序(简单字可以理解为音序) */ class StudentNameComparator
implements Comparator
{ public int compare(Student o1, Student o2) { return getGBK(o1.getName()).compareTo(getGBK(o2.getName())); } private String getGBK(String str) { byte[] bytes = null; try { bytes = str.getBytes( "gb2312 "); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } StringBuffer sb = new StringBuffer(); for(byte b : bytes) { sb.append(String.format( "%02X ", b)); } return sb.toString(); } }
自定义java排序
最新推荐文章于 2024-11-15 18:38:47 发布