List set sorting: Comparator, Collections. sort, and collections. sort

Source: Internet
Author: User

List set sorting: Comparator, Collections. sort, and collections. sort

Example

Package sortt; import java. util. arrayList; import java. util. collections; import java. util. comparator; import java. util. list; public class HomeWork {public static void main (String [] args) {List <Emp> EMS = new ArrayList <Emp> (); EMS. add (new Emp ("Terry", 25, 'M', 6000); EMS. add (new Emp ("Allen", 21, 'F', 4000); EMS. add (new Emp ("Smith", 23, 'M', 3000); System. out. println (EMS); // [(Terry, 25, m, 6000.0), (Allen, 21, f, 4000.0), (Smith, 23, m, 3000.0)] comparator <Emp> com = new Comparator <Emp> () {// anonymous internal class public int compare (Emp o1, Emp o2) {// TODO Auto-generated method stub return (int) (o1.getSalary ()-o2.getSalary () ;}}; Collections. sort (EMS, com); System. out. println (EMS); // [(Smith, 23, m, 3000.0), (Allen, 21, f, 4000.0), (Terry, 25, m, 6000.0)]}

 

 

Emp.java
class Emp{    private String name;    private int age;    private char gender;    private double salary;    public Emp(String name, int age, char gender, double salary) {        super();        this.name = name;        this.age = age;        this.gender = gender;        this.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 char getGender() {        return gender;    }    public void setGender(char gender) {        this.gender = gender;    }    public double getSalary() {        return salary;    }    public void setSalary(double salary) {        this.salary = salary;    }    public String toString(){        return "("+name+","+  age+"," +gender+"," + salary+")";            }        }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.