JAVA 1.8JDK LIST 分组排序写一段代码
时间: 2023-08-10 14:07:31 浏览: 180
JAVALIST排序.pdf
以下是 Java 1.8 JDK 中 List 分组排序的示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class ListGroupingAndSortingExample {
public static void main(String[] args) {
// Sample data
List<Employee> employees = Arrays.asList(
new Employee("John", "Doe", 1000),
new Employee("Jane", "Doe", 2000),
new Employee("John", "Smith", 1500),
new Employee("Jane", "Smith", 2500),
new Employee("Bob", "Johnson", 3000),
new Employee("Alice", "Johnson", 4000)
);
// Grouping by last name and sorting by salary
Map<String, List<Employee>> groupedAndSorted = employees.stream()
.sorted(Comparator.comparingInt(Employee::getSalary))
.collect(Collectors.groupingBy(Employee::getLastName));
// Printing results
groupedAndSorted.forEach((lastName, employeeList) -> {
System.out.println("Employees with last name " + lastName + ":");
employeeList.forEach(System.out::println);
});
}
}
class Employee {
private String firstName;
private String lastName;
private int salary;
public Employee(String firstName, String lastName, int salary) {
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getSalary() {
return salary;
}
@Override
public String toString() {
return firstName + " " + lastName + " (salary: " + salary + ")";
}
}
```
这个示例代码将员工列表按照姓氏进行分组,并且按照薪水进行排序。最后,它将每个分组中的员工列表打印出来。你可以根据自己的需求修改这个示例代码。
阅读全文