简体   繁体   中英

Convert String into ArrayList<Integer> with stream

I need to convert String into ArrayList.

String accountNumberValue = "151616165132132";

I try to do this but its look like hardcoded with double parsing char to String and Integer :

    ArrayList<Integer> accNumArray = accountNumberValue.chars()
                         .map((s)-> Integer.parseInt(String.valueOf(s)))
                         .collect(Collectors.toList());

Any easy way?

You can do it like that:

List<Integer> result=accountNumberValue
                     .chars()   //Get IntStream from a string with char codes
                     .map(Character::getNumericValue) //Map to the actual int
                     .boxed()  //Box the intstream 
                     .collect(Collectors.toList());  //Collect

You can do it with a single parsing by using split :

List<Integer> accNumArray = 
               Arrays.stream(accountNumberValue.split(""))
                     .map(Integer::parseInt)
                     .collect(Collectors.toList());

Perhaps not much of an improvement, but you could use Character#getNumericValue :

List<Integer> accNumArray = accountNumberValue.chars()
    .map(c -> new Integer(Character.getNumericValue(c)))
    .collect(Collectors.toList());

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