参考例子:
@Data
public class Student {
private String name;
private Integer age;
public static void main(String[] args) {
Student w1 = new Student();
w1.setName("w1");
w1.setAge(18);
Student w10 = new Student();
w10.setName("w10");
w10.setAge(18);
Student w2 = new Student();
w2.setName("w2");
w2.setAge(18);
List<Student> test = Stream.of(w1, w10, w2)
.sorted(Comparator.comparing((Student student) -> extractNumber(student.getName()))).toList();
// 打印学生信息
test.forEach(System.out::println);
}
private static int extractNumber(String title) {
StringBuilder numberBuilder = new StringBuilder();
for (char c : title.toCharArray()) {
if (Character.isDigit(c)) {
numberBuilder.append(c);
}
}
return !numberBuilder.isEmpty() ? Integer.parseInt(numberBuilder.toString()) : 0;
}
}