本文目录导读:

- 基础排序(Collections.sort)
- Stream API排序(Java 8+)
- 数据库排序查询(Spring Data JPA)
- 使用Pageable进行分页排序
- 自定义排序实现(复杂场景)
- 前端交互实现(Vue.js + Axios)
- 选择建议
- 性能优化建议
我将为您介绍Java中实现排序查询的几种常见方式,从基础到实战。
基础排序(Collections.sort)
使用Comparable接口
import java.util.*;
// 实体类实现Comparable
class Student implements Comparable<Student> {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
// 默认排序规则:按分数降序
@Override
public int compareTo(Student other) {
return Double.compare(other.score, this.score);
}
// getter和setter省略
@Override
public String toString() {
return String.format("Student{name='%s', age=%d, score=%.1f}", name, age, score);
}
}
public class SortExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 20, 95.5));
students.add(new Student("李四", 22, 88.0));
students.add(new Student("王五", 19, 92.5));
// 使用Comparable排序
Collections.sort(students);
System.out.println("按分数降序: " + students);
}
}
使用Comparator接口(推荐方式)
public class ComparatorExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 20, 95.5));
students.add(new Student("李四", 22, 88.0));
students.add(new Student("王五", 19, 92.5));
// 方式1:匿名内部类
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getAge(), s2.getAge());
}
});
System.out.println("按年龄升序: " + students);
// 方式2:Lambda表达式
Collections.sort(students, (s1, s2) -> s1.getName().compareTo(s2.getName()));
System.out.println("按姓名升序: " + students);
// 方式3:方法引用
Collections.sort(students, Comparator.comparing(Student::getScore).reversed());
}
}
Stream API排序(Java 8+)
import java.util.stream.Collectors;
public class StreamSortExample {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("张三", 20, 95.5),
new Student("李四", 22, 88.0),
new Student("王五", 19, 92.5)
);
// 单字段排序
List<Student> sortedByName = students.stream()
.sorted(Comparator.comparing(Student::getName))
.collect(Collectors.toList());
// 多字段排序:先按分数降序,再按年龄升序
List<Student> sortedByScoreAndAge = students.stream()
.sorted(Comparator.comparing(Student::getScore).reversed()
.thenComparing(Student::getAge))
.collect(Collectors.toList());
// 返回排序后的新列表(原列表不变)
students.stream()
.sorted(Comparator.comparing(Student::getScore))
.forEach(System.out::println);
}
}
数据库排序查询(Spring Data JPA)
实体类
import javax.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
@Column(name = "score")
private Double score;
// 构造函数、getter/setter省略
}
Repository接口
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.domain.Sort;
import java.util.List;
public interface StudentRepository extends JpaRepository<Student, Long> {
// 1. 使用Sort参数
List<Student> findAll(Sort sort);
// 2. 自定义查询方法(按分数降序)
List<Student> findByOrderByScoreDesc();
// 3. 条件排序查询
List<Student> findByAgeGreaterThanOrderByScoreDesc(Integer age);
}
Service层调用
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public List<Student> getSortedStudents(String sortField, String sortDirection) {
Sort sort = Sort.by(
sortDirection.equalsIgnoreCase("desc")
? Sort.Direction.DESC
: Sort.Direction.ASC,
sortField
);
return studentRepository.findAll(sort);
}
public List<Student> getStudentsWithPagination(int page, int size, String sortField) {
Pageable pageable = PageRequest.of(page, size, Sort.by(sortField).descending());
return studentRepository.findAll(pageable).getContent();
}
}
使用Pageable进行分页排序
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public ResponseEntity<Page<Student>> getStudents(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "score") String sortBy,
@RequestParam(defaultValue = "desc") String sortDir) {
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name())
? Sort.by(sortBy).ascending()
: Sort.by(sortBy).descending();
Pageable pageable = PageRequest.of(page, size, sort);
Page<Student> studentPage = studentRepository.findAll(pageable);
return ResponseEntity.ok(studentPage);
}
}
自定义排序实现(复杂场景)
public class AdvancedSortExample {
// 自定义排序算法示例:按多个属性组合排序
public static void complexSort(List<Student> students) {
students.sort((s1, s2) -> {
// 先按分数区间排序(90分以上为一档,以此类推)
int gradeLevel1 = getGradeLevel(s1.getScore());
int gradeLevel2 = getGradeLevel(s2.getScore());
if (gradeLevel1 != gradeLevel2) {
return Integer.compare(gradeLevel1, gradeLevel2);
}
// 同区间按分数降序
int scoreCompare = Double.compare(s2.getScore(), s1.getScore());
if (scoreCompare != 0) {
return scoreCompare;
}
// 分数相同按年龄升序
return Integer.compare(s1.getAge(), s2.getAge());
});
}
private static int getGradeLevel(double score) {
if (score >= 90) return 1;
if (score >= 80) return 2;
if (score >= 70) return 3;
return 4;
}
}
前端交互实现(Vue.js + Axios)
// 前端请求
getStudents({ page, size, sortField, sortOrder }) {
return axios.get('/api/students', {
params: {
page: page - 1,
size: size,
sortBy: sortField,
sortDir: sortOrder
}
});
}
// 表格排序组件
export default {
data() {
return {
sortField: 'score',
sortOrder: 'desc'
}
},
methods: {
handleSortChange(column) {
if (this.sortField === column.prop) {
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
} else {
this.sortField = column.prop;
this.sortOrder = 'asc';
}
this.fetchData();
}
}
}
选择建议
| 场景 | 推荐方式 | 原因 |
|---|---|---|
| 内存中少量数据排序 | Collections.sort + Lambda | 简单高效 |
| 流式处理数据 | Stream API | 函数式编程,代码简洁 |
| 数据库排序查询 | Spring Data JPA Sort | 利用数据库性能 |
| 大数据量分页排序 | Pageable | 支持分页,防止内存溢出 |
| 复杂排序规则 | 自定义Comparator | 灵活控制排序逻辑 |
性能优化建议
- 数据库排序:确保排序字段有索引
- 内存排序:数据量大时考虑并行流(
.parallelStream()) - 避免重复排序:缓存排序结果
- 使用稳定排序:
Collections.sort是稳定排序
需要我为您实现特定的排序场景吗?比如多表关联排序、动态字段排序等?
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播