Average salary of the employee
This code will implement the average salary of the employee with some conditions using java8.
1. We need to create the first Employeedata class.
2. Then we will write a mail class for average
Employeedata class
Employeeavg class
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeAvg {
public static void avgEmp() {
Employeedata E1=new Employeedata(122 ,23 ,"Tuku" ,300000 );
Employeedata E2=new Employeedata(122 ,23 ,"chuto",40000.0 );
Employeedata E3=new Employeedata(122 ,23 ,"Nathan",500000 );
Employeedata E4=new Employeedata(122 ,23 ,"Matham",600000 );
List<Employeedata> employees=new ArrayList<>();
employees.add(E4);
employees.add(E2);
employees.add(E1);
employees.add(E3);
double averageSalary = employees.stream().
filter(x ->x.getSalary()>50000)
.mapToDouble(Employeedata::getSalary)
.average()
.orElse(0.0);
System.out.println("Average salary: " + averageSalary);
double averageSalarys = employees.stream().collect(Collectors.averagingDouble(num -> num.getSalary()));
System.out.println("SimpleAverage salary: " + averageSalarys);
//Another way of averaging
double averageSalarym = employees.stream().
filter(x->x.getSalary()>50000).collect(Collectors.
averagingDouble(num -> num.getSalary()));
System.out.println("Average salary: " + averageSalarym);
}
public static void main(String [] args)
{
avgEmp();
}
}
import java.util.Objects;
public class Employeedata {
private int id;
private int age;
private String name;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString()
{
return "Employeedata [id=" + id + ", age=" + age + ", name=" + name + ", salary=" + salary + "]";
}
@Override
public int hashCode()
{
return Objects.hash(age, id, name, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employeedata other = (Employeedata) obj;
return
age == other.age && id == other.id && Objects.equals(name, other.name)&&Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary);
}
public Employeedata
(int id, int age, String name, double salary) {
super();
this.id = id;
this.age = age;
this.name = name;
this.salary = salary;
}
}
Program output :
Average salary: 466666.6666666667
SimpleAverage salary: 360000.0
Average salary: 466666.6666666667
No comments:
Add your comment