为了账号安全,请及时绑定邮箱和手机立即绑定

使用流将字符串转换为 ArrayList<Integer>

使用流将字符串转换为 ArrayList<Integer>

Smart猫小萌 2022-05-25 16:29:43
我需要将字符串转换为 ArrayList。String accountNumberValue = "151616165132132";我尝试这样做,但它看起来像用双重解析硬编码char到Stringand Integer:    ArrayList<Integer> accNumArray = accountNumberValue.chars()                          .map((s)-> Integer.parseInt(String.valueOf(s)))                          .collect(Collectors.toList());有什么简单的方法吗?
查看完整描述

3 回答

?
MM们

TA贡献1886条经验 获得超2个赞

您可以使用以下方法进行一次解析split

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


查看完整回答
反对 回复 2022-05-25
?
撒科打诨

TA贡献1934条经验 获得超2个赞

也许没有太大的改进,但您可以使用Character#getNumericValue

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


查看完整回答
反对 回复 2022-05-25
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

你可以这样做:

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


查看完整回答
反对 回复 2022-05-25
  • 3 回答
  • 0 关注
  • 159 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号