简体   繁体   中英

Sort ArrayList inside ArrayList

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]}

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());
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM