0

I am writing a component where it requires to sort upon Object variable parameter . For example : Employee has variable lastName. I want to sort the employees by the lastName.lenght() I have seen many examples,but i could not find an answer Can I achieve the result in this way or do we need a different approach.

I am giving the example

public class Employee {
    private int Id;
    private String firstName;
    private String lastName;
    private String department;

    public Employee(int id, String firstName, String lastName, String department) {
        Id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.department = department;
    }

    public Employee() {
    }

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        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;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "Id=" + Id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", department='" + department + '\'' +
                '}';
    }
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortExample
{
    public static void main(String[] args)
    {
        ArrayList<Employee> employees = getUnsortedEmployeeList();
        Comparator<Employee> compareByName = Comparator
                .comparing(Employee::getFirstName).reversed();

        Comparator<Employee> compareByLastName = Comparator
                .comparing(Employee::getLastName).reversed();


        
        List<Employee> sortedEmployees = employees.stream()
                .sorted(compareByName)
                .sorted(compareByLastName)
        //I have commented the code
        //.sorted((e1,e2) ->e1.getLastName().length().compareTo(e2.getLastName().length()))
                .collect(Collectors.toList());

        System.out.println(sortedEmployees);
    }

    private static ArrayList<Employee> getUnsortedEmployeeList()
    {
        ArrayList<Employee> list = new ArrayList<>();
        list.add( new Employee(2, "Irene", "Parr","programming") );
        list.add( new Employee(1, "Nicola", "Mitchell","programming") );
        list.add( new Employee(4, "Emily", "Carr","finance") );
        list.add( new Employee(5, "Blake", "Baker","finance") );
        list.add( new Employee(3, "Natalie", "Parsons","marketing") );
        list.add( new Employee(7, "Olivia", "Clarkson","marketing") );
        list.add( new Employee(6, "Justin", "Scott","marketing") );

        return list;
    }
}

Any help would be appreciated.

0

1 Answer 1

2

You might want to get familiar with Java 8 static methods of the Comparator interface like comparing(), comparingInt(), etc.

List<Employee> sortedEmployees = employees.stream()
    .sorted(Comparator.comparingInt(employee -> employee.getLastName().length()))
    .collect(Collectors.toList());

Also, don't sort the data multiple times (i.e. avoid applying sorted() more than once), instead you can chain the comparators by using different flavors of the method thenComparing().

Note, that if you don't need to create a copy of the list, then there's no point in utilizing streams. Instead, you can sort the source list by using List.sort().

Sign up to request clarification or add additional context in comments.

2 Comments

Good Answer. Even simpler: Skip the streaming, and just call Collections.sort.
@BasilBourque Only if unsorted list is no longer needed. And for this case since Java 8 we have List.sort().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.