简体   繁体   English

如何将String ArrayList的内容转换为char ArrayList

[英]How to convert contents of String ArrayList to char ArrayList

I currently have a String ArrayList with the contents [a, b, c, d, e...] and so forth. 我目前有一个包含内容[a,b,c,d,e ...]等的String ArrayList。 However, I need to have a character based arraylist (ArrayList name). 但是,我需要有一个基于字符的arraylist(ArrayList名称)。 How would I go upon looping through my String arraylist and converting its elements to char, to append to the char arraylist? 我如何遍历我的String arraylist并将其元素转换为char,以追加到char arraylist?

The same goes for converting a string arraylist full of numbers [1,2,3,4...] to an integer arraylist. 将充满数字[1,2,3,4 ...]的字符串数组列表转换为整数数组列表也是如此。 How would I go upon looping through, converting the type, and adding it to the new arraylist? 我如何遍历,转换类型并将其添加到新的arraylist中呢?

For the first problem just loop using a for and use the char charAt(0) method of string 对于第一个问题,只需使用for循环并使用string的char charAt(0)方法

List<String> arrayList;
List<Character> newArrayList = new ArrayList<>();

for( int i = 0; i < arrayList.size(); i++ ){
    String string = arrayList.at(i);
    newArrayList.add( string.charAt(0) ); // 0 becouse each string have only 1 char
}

for the second you can use Intenger.parseint 对于第二个您可以使用Intenger.parseint

List<String> arrayList;
List<int> newArrayList = new ArrayList<>();

for( int i = 0; i < arrayList.size(); i++ )
{
    String string = arrayList.at(i);
    newArrayList.add( Intenget.parseInt(string) );
}

As you said - you have to loop over the ArrayList : 如您所说-您必须遍历ArrayList

List<String> stringList = ...;
List<Character> charList = new ArrayList<>(old.size());

// assuming all the strings in old have one character, 
// as per the example in the question 
for (String s : stringList) {
    charList.add(s.charAt(0));
}

EDIT: 编辑:
You did not specify which java version you're using, but in Java 8 this can be done much more elegantly using the stream() method: 你没有指定你使用的Java版本,但在Java 8本可以优雅的使用来实现stream()方法:

List<Character> charList = 
    stringList.stream().map(s -> s.charAt(0)).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM