如何用单一行流式操作将空格分隔字符串转为Integer的ArrayList?
解决方法:用单一流式操作将字符串转为Integer类型的ArrayList
没问题,这确实是Java流式操作里一个容易踩的小坑,我给你两种单一行的流式实现方案,都能完美解决你的需求:
方案一:直接使用map保留包装类型
如果你不需要先处理基本类型int,直接用map(Integer::parseInt)就能得到Stream<Integer>,再收集成ArrayList即可:
ArrayList<Integer> numList = Arrays.stream("5 12 4".split(" ")) .map(Integer::parseInt) .collect(Collectors.toCollection(ArrayList::new));
- 这里用
Collectors.toCollection(ArrayList::new)而不是Collectors.toList(),是因为toList()返回的是一个通用的List实现(不一定是ArrayList),如果需要明确指定为ArrayList,这个方法更准确。
方案二:用boxed()将基本类型流转为包装类型流
如果你坚持想用mapToInt(比如需要先做一些int类型的中间操作),只需要在后面加一个boxed()方法,把IntStream装箱成Stream<Integer>,就能正常收集了:
ArrayList<Integer> numList = Arrays.stream("5 12 4".split(" ")) .mapToInt(Integer::parseInt) .boxed() .collect(Collectors.toCollection(ArrayList::new));
- 你之前的方法无效,核心原因是
mapToInt返回的是IntStream(基本类型流),而Collectors.toList()无法直接处理基本类型流,必须通过boxed()把每个int转换成Integer包装类型,变成对象流后才能用标准的收集器。
两种方案都是纯流式操作,不用写循环,完全符合你的需求~
内容的提问来源于stack exchange,提问作者jimboweb
相关产品推荐
相关产品推荐

