简体   繁体   中英

I want convert String to long

I have String like this ""3333"" I want convert to Long but when convert I am seeing this Exception

java.lang.NumberFormatException

I try many ways but I cant convert

I am trying this way

public void addNewFriend(List<String> mobileList, String login) {
    try {
        List<Long> list = new ArrayList<>();
        mobileList.forEach(x -> {
            log.debug(x);
            x=x.replace("\\\"","");
            Long y = Long.parseLong(x);
            log.debug(y.toString());
            list.add(y);
        });
        log.debug(list.toString());
        Set<AppUser> appUsers = appUserRepository.findByMobileNumberIn(list);
        if (appUsers.size() > 0) {
            AppUser appUser = appUserRepository.findByLogin(login);
            appUser.friends(appUsers);
            appUserRepository.save(appUser);
        } else {
            throw new BadRequestAlertException("cannot find user relation with author", "AppUser", "List is Empty");
        }
    } catch (NoSuchElementException e) {
        throw new BadRequestAlertException("Cannot find User", "Url", "Check your input");

    } catch (NullPointerException e) {
        throw new BadRequestAlertException("cannot find user relation with author", "AppUser", "List is Empty");

    } catch (Exception e) {
        throw new BadRequestAlertException(e.getMessage(), "Server Error", "Check it!");
    }


}

note: I am take this request from kafka I can't get mobile list in long direct

Remove the extra \\ because \\\" will look for \" which is not the case with your string.

public class Main {
    public static void main(String[] args) {
        System.out.println(Long.parseLong("\"3333\"".replace("\"", "")));
    }
}

Output:

3333

Just soultion change replace to replaceAll like this

    List<Long> list = new ArrayList<>();
mobileList.forEach(x -> {
    log.debug(x);
    x=x.replaceAll("\\\"","");
    Long y = Long.parseLong(x);
    log.debug(y.toString());
    list.add(y);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM