将逗号分隔的字符串转换为没有中间容器的列表 [英] convert comma separated string to list without intermediate container
本文介绍了将逗号分隔的字符串转换为没有中间容器的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将逗号分隔的字符串转换为整数列表。例如,如果我有以下字符串
I need to convert comma separated string to list of integers. For example if I have following string
String numbersArray = "1, 2, 3, 5, 7, 9,";
有没有办法如何将其一次转换为 List< Integer>
?
Is there a way how to convert it at once to List<Integer>
?
现在我只看到一种方法。
Now i see only one way to do it.
List<String> numbers = Arrays.asList(numbersArray.split(","));
然后
List<Integer> numbersInt = new ArrayList<>();
for (String number : numbers) {
numbersInt.add(Integer.valueOf(nubmer));
}
我很好奇有没有办法错过 List< String>
并在第一次开始时将其转换为 List< Integer>
I'm curious is there a way how to miss part with List<String>
and at the first onset convert it to List<Integer>
推荐答案
如果你使用的是Java 8,你可以:
If you're using Java 8, you can:
int[] numbers = Arrays.asList(numbersArray.split(","))
.stream()
.map(String::trim)
.mapToInt(Integer::parseInt).toArray();
如果没有,我认为您的方法是最佳选择。
If not, I think your approach is the best option available.
这篇关于将逗号分隔的字符串转换为没有中间容器的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文