可以使用 Java 8 的 stream API 和正则表达式来实现:

假设有一个对象类Person,其中有一个字段age表示年龄,可以按照如下方式进行排序:

List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", "26 years old"));
persons.add(new Person("Bob", "18 years old"));
persons.add(new Person("Charlie", "35 years old"));

// 排序
List<Person> sortedPersons = persons.stream()
        .sorted(Comparator.comparingInt(p -> Integer.parseInt(p.getAge().replaceAll("\\D+", ""))))
        .collect(Collectors.toList());

// 输出结果
sortedPersons.forEach(System.out::println);

其中,Comparator.comparingInt()方法可以根据指定的字段进行排序,而Integer.parseInt()replaceAll("\\D+", "")方法分别用于提取字符串中的数字和去除非数字字符

Java 如何只根据集合中对象某个字段中字符串中数字进行排序

原文地址: http://www.cveoy.top/t/topic/cUZY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录