如何使用Java Streams按转Int的字符串对象属性排序列表?
问题
我有一个包含String类型key属性的Book类对象列表,想用Java Streams的.sorted()方法把key转成int类型后排序,让key为"1"的Book对象排在首位。尝试了下面的代码但运行时抛出异常,请问代码里有什么问题?
示例Book类及初始化代码
public class Book { public String key; public String title; public Book(String key, String title) { this.key = key; this.title = title; } // Getters and Setters省略,假设已存在 } Book book1 = new Book("1", "A good book"); Book book2 = new Book("2", "A bad book"); List<Book> bookList = new ArrayList<>(); bookList.add(book2); bookList.add(book1);
尝试的排序代码
List<Book> sortedList = bookList.stream() .sorted(Comparator.comparingInt(b -> Integer.parseInt(b.getKey())) .collect(Collectors.toList());
问题分析与解决
你的代码存在两个问题:
- 括号不匹配:
.sorted()方法的调用缺少闭合括号,Comparator.comparingInt(...)后面少了一个),这会直接导致语法错误,连编译都无法通过,自然会引发运行异常。 - 潜在的数字格式异常风险:虽然示例里的
key都是合法数字字符串,但如果列表中存在无法转换为int的key(比如"abc"、空字符串),Integer.parseInt()会抛出NumberFormatException,这也是运行时异常的潜在诱因。
修正后的基础代码
先解决最直接的括号问题,修正后代码如下:
List<Book> sortedList = bookList.stream() .sorted(Comparator.comparingInt(b -> Integer.parseInt(b.getKey()))) .collect(Collectors.toList());
处理潜在的NumberFormatException(可选)
如果业务场景中可能出现非法格式的key,可以通过try-catch处理异常,给非法值设置默认排序逻辑,比如让这类对象排在最后:
List<Book> sortedList = bookList.stream() .sorted(Comparator.comparingInt(b -> { try { return Integer.parseInt(b.getKey()); } catch (NumberFormatException e) { return Integer.MAX_VALUE; } })) .collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者Slippy
相关产品推荐
相关产品推荐

