标签:sys prim eem str system false oar size other
一:实体类准备
public class Student{ private int id; private String name; private int age; public Student() { super(); System.out.println("Student:执行了!"); } public Student(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } @Override public int hashCode() { System.err.println("hashCode:方法执行了!"); final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { System.err.println("equals:方法执行了!"); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
二:List-Map 按年龄升排
@Test public void mapSort(){ //LinkedHashMap<Integer, Student> map = new LinkedHashMap<>(); //HashMap<Integer, Student> map = new HashMap<>(); TreeMap<Integer, Student> map = new TreeMap<>(); map.put(2, new Student(2,"ni",22)); map.put(1, new Student(1,"wo",11)); map.put(3, new Student(3,"ta",33)); //将map转换出成list List<Entry<Integer, Student>> list =new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Entry<Integer, Student>>() { @Override public int compare(Entry<Integer, Student> o1,Entry<Integer, Student> o2) { return o1.getValue().getAge()-(o2.getValue().getAge());//升序 } }); for (Entry<Integer, Student> entry : list) { System.out.println(entry.getValue()); } }
三:set 按年龄降序
@Test public void SetSort(){ Set<Student> set=new HashSet<>(); set.add(new Student(1,"wo",31)); set.add(new Student(2,"ni",22)); set.add(new Student(3,"ta",33)); List<Student> list = Arrays.asList(set.toArray(new Student[set.size()])); Collections.sort(list,new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getAge()-o1.getAge(); } }); for(Student s :list){ System.out.println(s); } }
标签:sys prim eem str system false oar size other
原文地址:https://www.cnblogs.com/lbky/p/10122959.html