1

How I can sort skills which is inside another ArrayList as descending order? We have an Employee class with id, name and skills. Skills is a separate list.

public static void main(String[] args) {

    List<Employee> employees = Arrays.asList(
            new Employee(101, "Ehsan", Arrays.asList("Java", "Spring Boot", "Hibernate", "Spring", "Java", "Net")),
            new Employee(102, "Jamshid", Arrays.asList("Java", "Marketing")),
            new Employee(103, "KK",
                    Arrays.asList("Payroll Management", "Human Resource", "Leaves", "Time Sheet")),
            new Employee(104, "Priya", Arrays.asList("Medicine", "Surgery")));


    
  
    
   for(Employee l: employees) {
       System.out.println(l);
   }

    
}

Expected o/p:
Ehsan : {[Java, Spring Boot, Hibernate, Spring, Java, Net]} 
KK : {[Payroll Management, Human Resource, Leaves, Time Sheet]} 
Jamshid : {[Java, Marketing]} 
Priya : {[Medicine, Surgery]}
4
  • If you need it all the time, the constructor of Employee could sort the list it gets. Commented Aug 13, 2020 at 22:19
  • Note that Arrays.asList does not return a java.util.ArrayList. Commented Aug 13, 2020 at 22:19
  • List itself has sort() in any contemporary Java version: docs.oracle.com/javase/8/docs/api/java/util/… - oh, maybe that remark was about the tag. Commented Aug 13, 2020 at 22:22
  • The expected output does'nt match your description. Commented Aug 13, 2020 at 22:31

1 Answer 1

1

You can use Comparator.comparingInt to sort based on the sizes of the skills List.

employees.sort(Comparator.<Employee>comparingInt(e -> e.getSkills().size()).reversed());

Before Java 8, you can use the following:

employees.sort(new Comparator<Employee>() {
    @Override
    public int compare(final Employee o1, final Employee o2) {
       return Integer.compare(o2.getSkills().size(), o1.getSkills().size());
    }
});
Sign up to request clarification or add additional context in comments.

8 Comments

For added fun, OP wanted descending order :-)
I mean with descending order this way: Ehsan has 6 skills so it comes first and KK has 4 skills and comes in second and so on.
Can you use Java 7 for your answer?
@ehsanhosseini Updated.
@ehsanhosseini Glad to help.
|

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.