1. 程式人生 > >集合排序案列

集合排序案列

arraylist true 集合排序 new hash obj linked code lec

一:實體類準備

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);
        }        
    }

集合排序案列