Если нам нужна только одна сортировка, например, по возросту, то нет смысла создавать отдельный класс. Можно сделать так:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainClass {

	public static void main(String args[]) {
		List<Worker> stud = new ArrayList<>();

		stud.add(new Worker("Alan", 85, "alan4@gmail.com"));
		stud.add(new Worker("Petrov", 30, "petrov@gmail.com"));
		stud.add(new Worker("Sidorov", 55, "sidorov@gmail.com"));
		stud.add(new Worker("Ivanov", 22, "ivanov@gmail.com"));
		stud.add(new Worker("Alan", 37, "alan1@gmail.com"));

		System.out.println("dont sort");
		System.out.println(stud);

		Comparator<Worker> SORT_BY_AGE = new Comparator<Worker>() {
			@Override
			public int compare(Worker w1, Worker w2) {
				return w1.getAge() - w2.getAge();
			}
		};

		Collections.sort(stud, SORT_BY_AGE);
		System.out.println("SORT BY AGE");
		System.out.println(stud);

	}
}

Ну и наш класс Worker:



public class Worker {
	private String name;
	private int age;
	private String email;
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	public Worker(String name, int age, String email) {
		this.name = name;
		this.age = age;
		this.email = email;
	}
	
	
	
	
	@Override
	public String toString() {
		return "name=" + name + ", age=" + age + ", email=" + email + "\n" ;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}
	/**
	 * @param email the email to set
	 */
	public void setEmail(String email) {
		this.email = email;
	}
}


Вывод на консоль:

dont sort
[name=Alan, age=85, email=alan4@gmail.com
, name=Petrov, age=30, email=petrov@gmail.com
, name=Sidorov, age=55, email=sidorov@gmail.com
, name=Ivanov, age=22, email=ivanov@gmail.com
, name=Alan, age=37, email=alan1@gmail.com
]
SORT BY AGE
[name=Ivanov, age=22, email=ivanov@gmail.com
, name=Petrov, age=30, email=petrov@gmail.com
, name=Alan, age=37, email=alan1@gmail.com
, name=Sidorov, age=55, email=sidorov@gmail.com
, name=Alan, age=85, email=alan4@gmail.com
]

Реклама