为什么不直接包裹lambda-body try...catch
?
您还可以null
在map
以下情况后过滤值:
intList = strList.stream()// same with "parallelStream()" .map(x -> { try { return Integer.parseInt(x); } catch (NumberFormatException nfe) { System.err.println(nfe.getMessage()); } return null; }) .filter(x -> x!= null) .collect(Collectors.toList());
这会给你想要的intList = [1,2,4,6]
.
编辑:要减少lamdba中try/catch的"沉重感",可以添加辅助方法.
static Integer parseIntOrNull(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException nfe) { System.err.println(nfe.getMessage()); } return null; } intList = strList.stream() .map(x -> parseIntOrNull(x)) .filter(x -> x!= null) .collect(Collectors.toList());
或者为了避免使用null,您可以返回Stream
static StreamparseIntStream(String s) { try { return Stream.of(Integer.parseInt(s)); } catch (NumberFormatException nfe) { System.err.println(nfe.getMessage()); } return Stream.empty(); } intList = strList.stream() .flatMap(x -> parseIntStream(x)) .collect(Collectors.toList());