Thursday, May 17, 2018

Sort employee object based on name

Problem statement: Sort employee object based on name !

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;

  5. class Employee {
  6. Integer id;
  7. String name;

  8. Employee(int id, String name) {
  9. this.id = id;
  10. this.name = name;
  11. }

  12. public String toString() {
  13. return "id: " + id + " -name: " + name;
  14. }
  15. }

  16. class SortByEmpName implements Comparator<Employee> {
  17. public int compare(Employee e1, Employee e2) {
  18. return e1.name.compareTo(e2.name);
  19. }
  20. }

  21. public class SortEmployee {

  22. public static void main(String[] args) {
  23. List<Employee> lists = new ArrayList<Employee>();
  24. lists.add(new Employee(23, "ishaan"));
  25. lists.add(new Employee(34, "raju"));
  26. lists.add(new Employee(2, "zebra"));
  27. lists.add(new Employee(43, "ch"));

  28. Collections.sort(lists, new SortByEmpName());
  29. for (Object o : lists) {

  30. System.out.println(o);
  31. }
  32. }
  33. }
Output:

id: 43 -name: ch
id: 23 -name: ishaan
id: 34 -name: raju
id: 2 -name: zebra

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...