How to Sort List of Employee by their name ? TCS Interview Question?

 Q. How to Sort List of Employee by their name ? Where we have fields like id, name and age.

Ans:-

Solution :-

Employee.java

package p4;

public class Employee {
private int id;
private String name;
private int 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;
}
public Employee(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

}

**************************************************************

EmployeeSortedByName.java

package p4;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class EmployeeSortedByName {

public static void main(String[] args) {
List<Employee> list=new ArrayList<>();
list.add(new Employee(5, "Devanshu", 50));
list.add(new Employee(3, "Mohan", 35));
list.add(new Employee(2, "Brajesh", 40));
list.add(new Employee(1, "Arpita", 26));
list.add(new Employee(4, "Jatin", 22));
List<Employee> sortedName=list.stream().sorted(Comparator.comparing(Employee::getName)).collect(Collectors.toList());
for(Employee e:sortedName) {
System.out.println("Sorted Name:"+e.getName());
}

}

}

*******************************************************




Comments

Popular posts from this blog

What are POJO classes in spring? What is the use of POJO Class, and How to create POJO classes.

How to create React project using command prompt?