Problem statement: Sort employee object based on name !
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- class Employee {
- Integer id;
- String name;
- Employee(int id, String name) {
- this.id = id;
- this.name = name;
- }
- public String toString() {
- return "id: " + id + " -name: " + name;
- }
- }
- class SortByEmpName implements Comparator<Employee> {
- public int compare(Employee e1, Employee e2) {
- return e1.name.compareTo(e2.name);
- }
- }
- public class SortEmployee {
- public static void main(String[] args) {
- List<Employee> lists = new ArrayList<Employee>();
- lists.add(new Employee(23, "ishaan"));
- lists.add(new Employee(34, "raju"));
- lists.add(new Employee(2, "zebra"));
- lists.add(new Employee(43, "ch"));
- Collections.sort(lists, new SortByEmpName());
- for (Object o : lists) {
- System.out.println(o);
- }
- }
- }
Output:
id: 43 -name: ch
id: 23 -name: ishaan
id: 34 -name: raju
id: 2 -name: zebra
No comments:
Post a Comment