Home > database >  Sorting list of Objects based on LastName, firstName in Java
Sorting list of Objects based on LastName, firstName in Java

Time:10-17

Problem: Sort list of Employees based on their lastNames. If lastNames are same then sort based on their firstNames. Sometimes, employee can be without lastName then firstName will be the lastName.

Employee names (lastName, firstName):

2238a Test1
2238 Test2
ven2215 ven
2238 Test3
"noLastName" Barry
"noLastName" Test4
"noLastName" Chuck
Far Steve

Expected Output:

2238 Test2
2238 Test3
2238a Test1
 Barry
 Chuck 
Far Steve
 Test4
ven2215 ven

Here is the code I have written but getting the wrong output.

import java.util.ArrayList;
import java.util.List;

public class sortingSample {

    public static void main(String[] args) {

        Employee emp1 = new Employee();
        Employee emp2 = new Employee();
        Employee emp3 = new Employee();
        Employee emp4 = new Employee();
        Employee emp5 = new Employee();
        Employee emp6 = new Employee();
        Employee emp7 = new Employee();
        Employee emp8 = new Employee();

        emp1.setId(1);
        emp1.setFirstName("Test1");
        emp1.setLastName("2238a");

        emp2.setId(2);
        emp2.setFirstName("Test2");
        emp2.setLastName("2238");

        emp8.setId(8);
        emp8.setFirstName("ven");
        emp8.setLastName("ven2215");

        emp3.setId(3);
        emp3.setFirstName("Test3");
        emp3.setLastName("2238");

        emp5.setId(5);
        emp5.setFirstName("Barry");
        emp5.setLastName("");

        emp4.setId(4);
        emp4.setFirstName("Test4");
        emp4.setLastName("");

        emp6.setId(6);
        emp6.setFirstName("Chuck");
        emp6.setLastName("");

        emp7.setId(7);
        emp7.setFirstName("Steve");
        emp7.setLastName("Far");

        List<Employee> employees = new ArrayList<Employee>();

        employees.add(emp1);
        employees.add(emp2);
        employees.add(emp3);
        employees.add(emp4);
        employees.add(emp5);
        employees.add(emp6);
        employees.add(emp7);
        employees.add(emp8);

        employees.sort((p1, p2) -> {
            int i = 0;

            if ((p1.getLastName().length() == 0) && (p2.getLastName().length() != 0)) {
                i = p2.getFirstName().compareToIgnoreCase(p1.getLastName());
                return i;
            }

            else if (p2.getLastName().length() == 0 && !(p1.getLastName().length() != 0)) {
                i = p1.getFirstName().compareToIgnoreCase(p2.getLastName());
                return i;
            }
            
            else {
                i = p1.getLastName().compareToIgnoreCase(p2.getLastName());
                if (i != 0) {
                    return i;
                }
                i = p1.getFirstName().compareTo(p2.getFirstName());
                return i;
            }
        });

        for (Employee e : employees) {
            System.out.println(e.getLastName()   " "   e.getFirstName());
        }
    }
}

class Employee {

    Integer id;
    String firstName;
    String lastName;
    
    public Integer getId() 
    {
        return id;
    }
    
    public void setId(Integer id) 
    {
        this.id = id;
    }
    
    public String getFirstName() 
    {
        return firstName;
    }
    
    public void setFirstName (String firstName) 
    {
        this.firstName = firstName;
    }
    
    public String getLastName () 
    {
        return lastName;
    }
    
    public void setLastName (String lastName) 
    {
        this.lastName = lastName;
    }
    
}

My program output:

2238 Test2
2238 Test3
2238a Test1
 Test4
 Barry
 Chuck
Far Steve
ven2215 ven

CodePudding user response:

Try this.

record Employee(int id, String firstName, String lastName) {}

List<Employee> employees = Arrays.asList(
    new Employee(1, "Test1", "2238a"),
    new Employee(2, "Test2", "2238"),
    new Employee(8, "ven", "ven2215"),
    new Employee(3, "Test3", "2238"),
    new Employee(5, "Barry", ""),
    new Employee(4, "Test4", ""),
    new Employee(6, "Chuck", ""),
    new Employee(7, "Steve", "Far"));

employees.sort(Comparator.comparing(e ->
    (e.lastName().length() == 0
        ? e.firstName()
        : e.lastName()   " "   e.firstName()).toLowerCase()));

employees.forEach(System.out::println);

output:

Employee[id=2, firstName=Test2, lastName=2238]
Employee[id=3, firstName=Test3, lastName=2238]
Employee[id=1, firstName=Test1, lastName=2238a]
Employee[id=5, firstName=Barry, lastName=]
Employee[id=6, firstName=Chuck, lastName=]
Employee[id=7, firstName=Steve, lastName=Far]
Employee[id=4, firstName=Test4, lastName=]
Employee[id=8, firstName=ven, lastName=ven2215]

When sorting after grouping by department:

record Employee(int id, String firstName, String lastName, String department) {}

List<Employee> employees = Arrays.asList(
    new Employee(1, "Test1", "2238a", "A"),
    new Employee(2, "Test2", "2238", "B"),
    new Employee(8, "ven", "ven2215", "A"),
    new Employee(3, "Test3", "2238", "B"),
    new Employee(5, "Barry", "", "A"),
    new Employee(4, "Test4", "", "B"),
    new Employee(6, "Chuck", "", "A"),
    new Employee(7, "Steve", "Far", "B"));

Map<String, List<Employee>> result = employees.stream()
    .collect(Collectors.groupingBy(Employee::department,
        Collectors.collectingAndThen(Collectors.toList(),
            x -> x.stream()
                .sorted(Comparator.comparing(e ->
                    (e.lastName().length() == 0
                        ? e.firstName()
                        : e.lastName()   " "   e.firstName()).toLowerCase()))
                .collect(Collectors.toList()))));

for (Entry<String, List<Employee>> p : result.entrySet()) {
    System.out.println(p.getKey());
    for (Employee e : p.getValue())
        System.out.println("  "   e);
}

output:

A
  Employee[id=1, firstName=Test1, lastName=2238a, department=A]
  Employee[id=5, firstName=Barry, lastName=, department=A]
  Employee[id=6, firstName=Chuck, lastName=, department=A]
  Employee[id=8, firstName=ven, lastName=ven2215, department=A]
B
  Employee[id=2, firstName=Test2, lastName=2238, department=B]
  Employee[id=3, firstName=Test3, lastName=2238, department=B]
  Employee[id=7, firstName=Steve, lastName=Far, department=B]
  Employee[id=4, firstName=Test4, lastName=, department=B]

CodePudding user response:

I want to give a few recommendations about your question. Try to process in SQL if your data comes in from database and sorting processing required, otherwise you have to do twice as much surgery. as I understand it looks like you just want to practice if so then try to write sorting process into Stream API. There are pretty methods,which are sorting processing like well.

  • Related