Java 8 将整数字符串转换为 List<Integer>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40869365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 convert String of ints to List<Integer>
提问by Igor
I have a String:
我有一个字符串:
String ints = "1, 2, 3";
I would like to convert it to a list of ints:
我想将其转换为整数列表:
List<Integer> intList
I am able to convert it to a list of strings this way:
我可以通过这种方式将其转换为字符串列表:
List<String> list = Stream.of("1, 2, 3").collect(Collectors.toList());
But not to list of ints.
但不是整数列表。
Any ideas?
有任何想法吗?
回答by Tunaki
You need to split the string and make a Stream out of each parts. The method splitAsStream(input)
does exactly that:
您需要拆分字符串并从每个部分制作一个流。该方法splitAsStream(input)
正是这样做的:
Pattern pattern = Pattern.compile(", ");
List<Integer> list = pattern.splitAsStream(ints)
.map(Integer::valueOf)
.collect(Collectors.toList());
It returns a Stream<String>
of the part of the input string, that you can later map to an Integer
and collect into a list.
它返回Stream<String>
输入字符串的一部分,您可以稍后将其映射到Integer
并收集到列表中。
Note that you may want to store the pattern in a constant, and reuse it each time it is needed.
请注意,您可能希望将模式存储在一个常量中,并在每次需要时重用它。
回答by Lukas Eder
Regular expression splitting is what you're looking for
正则表达式拆分正是您要找的
Stream.of(ints.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
回答by tobias_k
First, split the string into individual numbers, then convert those (still string) to actual integers, and finally collect them in a list. You can do all of this by chaining stream operations.
首先,将字符串拆分为单独的数字,然后将这些(仍然是字符串)转换为实际的整数,最后将它们收集到一个列表中。您可以通过链接流操作来完成所有这些。
String ints = "1, 2, 3";
List<Integer> intList = Stream
.of(ints.split(", "))
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(intList); // [1, 2, 3]
回答by tl-photography.at
You can just use the Array function asList, and then convert it the java8 way.
您可以只使用Array函数asList,然后将其转换为java8方式。
Don't forget to remove the white spaces.
不要忘记删除空格。
List<Integer> erg = Arrays.asList(ints.replace(" ", "").split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
EDIT: Sorry i didn't see that it was a single string, thought it was a array of String.
编辑:对不起,我没有看到它是一个单一的字符串,以为它是一个字符串数组。