Browse Source

套题分类按首字母排序

master
luogw 2 months ago
parent
commit
a60e87265c
  1. 49
      src/main/java/com/project/classicpaper/application/impl/ClassicCategoryApplicationServiceImpl.java

49
src/main/java/com/project/classicpaper/application/impl/ClassicCategoryApplicationServiceImpl.java

@ -15,6 +15,7 @@ import com.project.classicpaper.domain.service.ClassicPaperSetBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;
@ -29,11 +30,11 @@ public class ClassicCategoryApplicationServiceImpl implements ClassicCategoryApp
@Override
public Result<List<ClassicCategoryDTO>> treeList(Boolean withPaperSet) {
// 1. 查所有分类 → DTO
List<ClassicCategoryDTO> list = classicCategoryBaseService.list(
new LambdaQueryWrapper<ClassicCategoryEntity>().orderByAsc(ClassicCategoryEntity::getSort)
).stream().map(entity -> entity.toDTO(ClassicCategoryDTO::new))
// 1. 查所有分类 → DTO(Java 中排序)
List<ClassicCategoryDTO> list = classicCategoryBaseService.list()
.stream().map(entity -> entity.toDTO(ClassicCategoryDTO::new))
.collect(Collectors.toList());
list.sort(this::compareByName);
// 2. 构建树
List<ClassicCategoryDTO> tree = TreeUtils.buildLongTree(list,
@ -69,6 +70,46 @@ public class ClassicCategoryApplicationServiceImpl implements ClassicCategoryApp
return Result.success(tree);
}
/**
* 按名称排序规则
* - 中文 按拼音首字母使用 java Collator
* - 英文 按字母顺序
* - 其他 ID
*/
private int compareByName(ClassicCategoryDTO a, ClassicCategoryDTO b) {
String nameA = a.getName();
String nameB = b.getName();
int typeA = getCharType(nameA);
int typeB = getCharType(nameB);
if (typeA != typeB) {
return Integer.compare(typeA, typeB);
}
if (typeA == 0) {
return Collator.getInstance(Locale.CHINESE).compare(
nameA != null ? nameA : "",
nameB != null ? nameB : "");
} else if (typeA == 1) {
String safeA = nameA != null ? nameA : "";
String safeB = nameB != null ? nameB : "";
return safeA.compareToIgnoreCase(safeB);
} else {
return Long.compare(
a.getId() != null ? a.getId() : 0L,
b.getId() != null ? b.getId() : 0L);
}
}
/**
* 判断首字符类型0-中文1-英文2-其他
*/
private int getCharType(String name) {
if (name == null || name.isEmpty()) return 2;
char first = name.charAt(0);
if (first >= '一' && first <= '鿿') return 0;
if ((first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z')) return 1;
return 2;
}
/**
* 递归注入 paperSetCount
* 二级节点取直接统计值一级节点累加子节点

Loading…
Cancel
Save