最近几天在笔试过程中,遇到一些排序的问题,比如对于集合中的元素进行排序,集合中的元素是类,比如员工类,它有年龄和薪水,现在根据年龄排序。可以使用java中的工具类Collections。
List排序
public class ListSortedMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* 对集合中的元素进行排序,主要是对年龄,从小到大
*/
public static void listSorted() {
Eploeer eploeer = new Eploeer("小明",10,10.0f);
Eploeer eploeer2 = new Eploeer("小张",13,11.0f);
Eploeer eploeer3 = new Eploeer("小李",12,12.0f);
List<Eploeer> list = new ArrayList();
list.add(eploeer);
list.add(eploeer2);
list.add(eploeer3);
//排序
Collections.sort(list, new Comparator<Eploeer>() {
@Override
public int compare(Eploeer o1, Eploeer o2) {
// TODO Auto-generated method stub
return (int)(o1.getAge() - o2.getAge());
}
});
System.out.println(list);
}
}
class Eploeer {
private String name;
private int age;
private float salary;
public Eploeer() {
}
public Eploeer(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Eploeer [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
TreeSet排序
字典排序
/**
* 指定薪水自然排序
*/
public static void treeSetSortedDistin() {
Eploeer eploeer = new Eploeer("小明",10,10.0f);
Eploeer eploeer2 = new Eploeer("小张",13,11.0f);
Eploeer eploeer3 = new Eploeer("小李",12,12.0f);
TreeSet<Eploeer> treeSet = new TreeSet(new Comparator<Eploeer>() {
@Override
public int compare(Eploeer o1, Eploeer o2) {
// TODO Auto-generated method stub
return (int) (o1.getSalary() - o2.getSalary());
}
});
treeSet.add(eploeer);
treeSet.add(eploeer2);
treeSet.add(eploeer3);
System.out.println(treeSet);
}
自定义排序
public static void treeSetSortedDef() {
Eploeer eploeer = new Eploeer("小明",10,10.0f);
Eploeer eploeer2 = new Eploeer("小张",13,11.0f);
Eploeer eploeer3 = new Eploeer("小李",12,12.0f);
TreeSet<Eploeer> treeSet = new TreeSet();
treeSet.add(eploeer);
treeSet.add(eploeer2);
treeSet.add(eploeer3);
System.out.println(treeSet);
}
class Eploeer implements Comparable<Eploeer>{
private String name;
private int age;
private float salary;
public Eploeer() {
}
public Eploeer(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Eploeer [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public int compareTo(Eploeer o) {
// TODO Auto-generated method stub
return this.getAge() - o.getAge();
}
}