如何使用 Java StreamAPI 处理 NumberFormatException

knö*_*del 7 java exception numberformatexception java-stream

有没有办法过滤掉所有大于可以存储在Long使用 Stream API 中的最大值的值?

目前的情况是,您可以通过一些客户的 ID 在前端通过简单的搜索栏进行搜索。

例如:123456789, 10987654321.如果您在这两个 ID 之间放置一个“分隔符”,则一切正常。但是,如果您忘记了“分隔符”,我的代码将尝试解析12345678910987654321为 Long,我想就存在问题了。

这会导致NumberFormatException尝试搜索后。Long有没有办法过滤掉这些因太大而无法解析为 a 的数字?

String hyphen = "-";

String[] customerIds = bulkCustomerIdProperty.getValue()
              .replaceAll("[^0-9]", hyphen)
              .split(hyphen);
...
customerFilter.setCustomerIds(Arrays.asList(customerIds).stream()
              .filter(n -> !n.isEmpty()) 
              .map(n -> Long.valueOf(n)) // convert to Long
              .collect(Collectors.toSet()));
Run Code Online (Sandbox Code Playgroud)

Ale*_*nko 8

您可以将解析提取到单独的方法中并用 包装它try/catch,或者使用BigInteger来消除超出范围的值long

示例BigInteger

Set<Long> result =  Stream.of("", "12345", "9999999999999999999999999999")
        .filter(n -> !n.isEmpty())
        .map(BigInteger::new)
        .filter(n -> n.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0 &&
                     n.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) >= 0)
        .map(BigInteger::longValueExact) // convert to Long
        .peek(System.out::println) // printing the output
        .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

NumberFormatException在单独的方法中处理的示例:

Set<Long> result =  Stream.of("", "12345", "9999999999999999999999999999")
        .filter(n -> !n.isEmpty())
        .map(n -> safeParse(n))
        .filter(OptionalLong::isPresent)
        .map(OptionalLong::getAsLong) // extracting long primitive and boxing it into Long
        .peek(System.out::println) // printing the output
        .collect(Collectors.toSet());

public static OptionalLong safeParse(String candidate) {
    try {
        return OptionalLong.of(Long.parseLong(candidate));
    } catch (NumberFormatException e) {
        return OptionalLong.empty();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出(来自peek()

12345
Run Code Online (Sandbox Code Playgroud)

  • @Dai [Lil' Exception 的卓越性能](https://shipilev.net/blog/2014/exceptional-performance/) (2认同)