Java 将逗号分隔的字符串转换为没有中间容器的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27599847/
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
convert comma separated string to list without intermediate container
提问by user3127896
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,";
Is there a way how to convert it at once to List<Integer>
?
有没有办法立即将其转换为List<Integer>
?
Now i see only one way to do it.
现在我只看到一种方法。
List<String> numbers = Arrays.asList(numbersArray.split(","));
And then
进而
List<Integer> numbersInt = new ArrayList<>();
for (String number : numbers) {
numbersInt.add(Integer.valueOf(nubmer));
}
I'm curious is there a way how to miss part with List<String>
and at the first onset convert it to List<Integer>
我很好奇有没有办法如何错过部分List<String>
并在第一次发作时将其转换为List<Integer>
采纳答案by Maroun
If you're using Java 8, you can:
如果您使用的是 Java 8,则可以:
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.
如果没有,我认为您的方法是可用的最佳选择。
回答by Paul Boddington
This works, as long as the String
ends in a comma, like your example.
只要以String
逗号结尾,就可以工作,就像您的示例一样。
String numbersArray = "1, 2, 3, 14, 5,";
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, j, n = numbersArray.length(); i < n; i = j + 1) {
j = numbersArray.indexOf(",", i);
list.add(Integer.parseInt(numbersArray.substring(i, j).trim()));
}
However, it's pretty useless, as on my machine it's about 2 times slower than the original.
但是,它非常没用,因为在我的机器上它比原始机器慢了大约 2 倍。
This next solution, on the other hand, is surprisingly fast. I tested it on lists of 50000 integers obtained using Math.abs(random.nextInt())
and it was about 4 times faster than the original.
另一方面,下一个解决方案出奇地快。我在使用获得的 50000 个整数的列表上对其进行了测试,它Math.abs(random.nextInt())
比原始值快了大约 4 倍。
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
char c = numbersArray.charAt(i);
if (c == ',') {
list.add(a);
a = 0;
} else if (c != ' ') {
a = a * 10 + (c - '0');
}
}
And this is about twice as fast again:
这又快了两倍:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
switch(numbersArray.charAt(i)) {
case ',': list.add(a); a = 0; break;
case ' ': break;
case '0': a = a * 10; break;
case '1': a = a * 10 + 1; break;
case '2': a = a * 10 + 2; break;
case '3': a = a * 10 + 3; break;
case '4': a = a * 10 + 4; break;
case '5': a = a * 10 + 5; break;
case '6': a = a * 10 + 6; break;
case '7': a = a * 10 + 7; break;
case '8': a = a * 10 + 8; break;
case '9': a = a * 10 + 9; break;
default: throw new AssertionError();
}
}
回答by David Soroko
If you are willing to use Google Guava ( https://code.google.com/p/guava-libraries/) , splitter is your friend
如果您愿意使用 Google Guava ( https://code.google.com/p/guava-libraries/) ,splitter 是您的朋友
List<Integer> list = new ArrayList<Integer>();
for ( String s : Splitter.on(',').trimResults().omitEmptyStrings().split("1, 2, 3, 14, 5,") ) {
list.add(Integer.parseInt(s));
}
or, you could use something similar to your original approach and:
或者,您可以使用类似于原始方法的方法,并且:
List<Integer> list = new ArrayList<Integer>();
for (String s :"1, 2, 3, 5, 7, 9,".split(",") ) {
list.add(Integer.parseInt(s.trim()));
}
回答by santosh Kumar
I think below piece of code could be helpful for you.
我认为下面的一段代码可能对你有帮助。
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws java.io.IOException {
String numbersArray = "1, 2, 3, 5, 7, 9,";
System.out.println(numbersArray);
Scanner sc = new Scanner(numbersArray);
sc.useDelimiter("(, *)*");
try{
while(true){
System.out.println(sc.nextInt());
}
} catch (Exception e) {
System.out.println("reading is completed");
}
}
}
Instead of using System.out.println add it to the Integer list.
而不是使用 System.out.println 将它添加到整数列表中。
Here we are not traversing through the complete list multiple times, instead we traverse only once and storing them in array.
这里我们没有多次遍历完整列表,而是只遍历一次并将它们存储在数组中。
回答by wassgren
I really like @MarounMaroun's answer but I wonder if it is even better to use the Arrays.stream
-method instead of Arrays.asList
.
我真的很喜欢@MarounMaroun 的回答,但我想知道使用Arrays.stream
-method 而不是Arrays.asList
.
int[] numbers = Arrays.stream(numbersArray.split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
This SO-questiondiscusses this further and summarizes it as such:
这个 SO-question进一步讨论了这一点并将其总结如下:
because you leave the conversion of the array to a stream to the JDK - let it be responsible for efficiency etc.
因为您将数组到流的转换留给了 JDK - 让它负责效率等。
回答by Mohsen Kashi
Using java 8 Streams:
使用 java 8 流:
List<Integer> longIds = Stream.of(commaSeperatedString.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
回答by Bandi Kishore
If you're not on java8, then you can use Guava
如果你不在 java8 上,那么你可以使用Guava
Lists.transform(Arrays.asList(numbersArray.split(",")), new Function<String, Integer>() {
@Override
public Integer apply(String input) {
return Integer.parseInt(input.trim());
}
});
As @Maroun has mentioned for Java8 you can use Streams.
正如@Maroun 提到的 Java8,您可以使用 Streams。
int[] numbers = Arrays.asList(numbersArray.split(","))
.stream()
.map(String::trim)
.mapToInt(Integer::parseInt).toArray();