Issue
I'm sorting the Employee Data by grouping the employee number and employee salary. Excepted output I got, but I need to store this details in a fixedlength file. So I need to print by below format.
public class SortData {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("102", "300", "100", "200"),
new Employee("101", "200", "80", "120"),
new Employee("102", "100", "50", "50"),
new Employee("103", "300", "100", "200"),
new Employee("101", "200", "80", "120"),
new Employee("101", "100", "50", "50"));
Map<String, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getEmpNo,
Collectors.groupingBy(Employee::getEmpSal)));
System.out.println(map);
}
}
class Employee {
private String empNo;
private String empSal;
private String empHra;
private String empPf;
// getter
// setter
}
The above code's output is as below.
{101={100=[Employee(empNo=101, empSal=100, empHra=50, empPf=50)], 200=[Employee(empNo=101,
empSal=200, empHra=80, empPf=120), Employee(empNo=101, empSal=200, empHra=80, empPf=120)]},
102={100=[Employee(empNo=102, empSal=100, empHra=50, empPf=50)], 300=[Employee(empNo=102,
empSal=300, empHra=100, empPf=200)]},
103={300=[Employee(empNo=103, empSal=300, empHra=100, empPf=200)]}}
I need to print this out put in a fixedlength file. So I need the output as below.
1011005050
10120080120
10120080120
1021005050
102300100200
103300100200
Can anyone please help me on this.
Solution
First, the maps in current implementation are NOT sorted.
Second, it may be redundant to sort the maps. It appears that in order to print the input data, just the input list needs to be sorted by empNo
and empSal
:
Comparator<Employee> sortByNoAndSal = Comparator
.comparing(Employee::getEmpNo)
.thenComparing(Employee::getEmpSal);
employees.sort(sortByNoAndSal);
Last, to print/output an instance of Employee
specific method should be implemented (by overriding Employee::toString
, or creating specific method). Aside note - required output seems to be missing a delimiter between fields of Employee
.
// class PrintData
public static void printEmployee(Employee emp) {
String delimiter = ""; // fix if necessary
System.out.println(String.join(delimiter, emp.getNo(), emp.getSal(), emp.getHra(), emp.getPf()));
}
// invoke this method
employees.forEach(PrintData::printEmployee);
Answered By - Nowhere Man
Answer Checked By - Clifford M. (JavaFixing Volunteer)