How to check if a String is numeric in Java

前端 未结 30 2517
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  无人及你
    2020-11-21 05:45

    Java 8 Stream, lambda expression, functional interface

    All cases handled (string null, string empty etc)

    String someString = null; // something="", something="123abc", something="123123"
    
    boolean isNumeric = Stream.of(someString)
                .filter(s -> s != null && !s.isEmpty())
                .filter(Pattern.compile("\\D").asPredicate().negate())
                .mapToLong(Long::valueOf)
                .boxed()
                .findAny()
                .isPresent();
    

提交回复
热议问题