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

目前的情况是,你可以在前端用一个简单的搜索栏搜索一些客户的身份证.

例如:123456789, 10987654321.如果你在这两个ID之间加一个"separator",那么一切都正常.但是如果你忘记了"separator",我的代码试图把12345678910987654321解析成一个长的,我想这就是问题所在.

这会在try 搜索后导致NumberFormatException分.有没有办法过滤掉那些因为太大而无法解析成Long的数字?

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()));

推荐答案

您可以将解析提取到一个单独的方法中,并将其包装为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());

使用单独方法处理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();
    }
}

Output(从peek()开始)

12345

Java相关问答推荐

BiPredicate和如何使用它

Quarkus keycloat配置不工作.quarkus. keycloak. policy—enforcer. enable = true在. yaml表示中不工作

JDK22执行repackage of goal org. springframework. boot:spring—boot—maven—plugin:3.2.3:repackage failed:unsupported class file major version 66—>

弹簧靴和龙目岛

为什么在枚举中分支预测比函数调用快?

如何让JFileChooser(DIRECTORIES_ONLY)从FolderName中的空白开始?

Hibernate 6支持Joda DateTime吗?

通过合并Akka Streams中的多个慢源保持订购

Spring Boot 3.2.2中的@Inject和@Resource Remove

如何创建一个2d自上而下的移动系统,其中移动,同时持有两个关键是可能的处理?

获取字符串中带空格的数字和Java中的字符

用户填充的数组列表永不结束循环

声明MessageChannel Bean的首选方式

MimeMessage emlMessage=new MimeMessage(Session,emlInputStream);抛出InvocationTargetException

垃圾收集时间长,会丢弃网络连接,但不会在Kubernetes中反弹Pod

为什么在下面的Java泛型方法中没有类型限制?

如果List是一个抽象接口,那么Collectors.toList()如何处理流呢?

为什么JavaFX MediaPlayer音频播放在Windows和Mac上运行良好,但在Linux(POPOS/Ubuntu)上却有问题?

将@Transactional添加到Spring框架中链下的每个方法会产生什么效果?

为什么我得到默认方法的值而不是被覆盖的方法的值?