英文:
Sort ArrayList inside ArrayList
问题
以下是您要翻译的代码部分:
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);
}
}
期望的输出:
Ehsan : {[Java, Spring Boot, Hibernate, Spring, Java, Net]}
KK : {[Payroll Management, Human Resource, Leaves, Time Sheet]}
Jamshid : {[Java, Marketing]}
Priya : {[Medicine, Surgery]}
英文:
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]}
答案1
得分: 1
你可以使用 Comparator.comparingInt
来根据技能 List
的大小进行排序。
employees.sort(Comparator.<Employee>comparingInt(e -> e.getSkills().size()).reversed());
在Java 8之前,你可以使用以下方式:
@Override
public int compare(final Employee o1, final Employee o2) {
return Integer.compare(o2.getSkills().size(), o1.getSkills().size());
}
});```
<details>
<summary>英文:</summary>
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());
}
});
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论