简体   繁体   English

将 ArrayList 个字符转换为字符串?

[英]Converting ArrayList of Characters to a String?

How to convert an ArrayList<Character> to a String in Java?如何将ArrayList<Character>转换为 Java 中的String

The List.toString method returns it as [a,b,c] string - I want to get rid of the brackets (etcetera) and store it as abc . List.toString方法将其作为[a,b,c]字符串返回 - 我想去掉括号(等等)并将其存储为abc

You can iterate through the list and create the string.您可以遍历列表并创建字符串。

String getStringRepresentation(ArrayList<Character> list)
{    
    StringBuilder builder = new StringBuilder(list.size());
    for(Character ch: list)
    {
        builder.append(ch);
    }
    return builder.toString();
}

Setting the capacity of the StringBuilder to the list size is an important optimization.StringBuilder的容量设置为列表大小是一项重要的优化。 If you don't do this, some of the append calls may trigger an internal resize of the builder.如果您不这样做,一些append调用可能会触发构建器的内部调整大小。

As an aside, toString() returns a human-readable format of the ArrayList's contents.顺便说一句, toString()返回 ArrayList 内容的人类可读格式。 It is not worth the time to filter out the unnecessary characters from it.不值得花时间从中过滤掉不必要的字符。 It's implementation could change tomorrow, and you will have to rewrite your filtering code.它的实现明天可能会改变,你将不得不重写你的过滤代码。

Here a possible one-line solution using Java8 streams.这是使用 Java8 流的一种可能的单行解决方案。

a) List of Character objects to String: a) 字符串的字符对象列表:

String str = chars.stream()
                  .map(e->e.toString())
                  .reduce((acc, e) -> acc  + e)
                  .get();

b) array of chars (char[] chars) b) 字符数组(char[] 字符)

String str = Stream.of(chars)
                   .map(e->new String(e))
                   .reduce((acc, e) -> acc  + e)
                   .get();

UPDATE (following comment below):更新(以下评论):

a) List of Character objects to String: a) 字符串的字符对象列表:

String str = chars.stream()
                  .map(e->e.toString())
                  .collect(Collectors.joining());

b) array of chars (char[] chars) b) 字符数组(char[] 字符)

String str = Stream.of(chars)
                   .map(e->new String(e))
                   .collect(Collectors.joining());

Note that the map(e->e.toString()) step in the above solutions will create a temporary string for each character in the list.请注意,上述解决方案中的map(e->e.toString())步骤将为列表中的每个字符创建一个临时字符串。 The strings immediately become garbage.琴弦立即变成垃圾。 So, if the performance of the conversion is a relevant concern, you should consider using the StringBuilder approach instead.因此,如果转换的性能是一个相关问题,您应该考虑改用StringBuilder方法

How about this, Building the list这个怎么样,建立清单

List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');

Actual code to get String from List of Character:从字符列表中获取字符串的实际代码:

String word= new String();
for(char c:charsList){
word= word+ c; 
}
System.out.println(word);

Still learning if there is a misake point out.如果有错误指出,仍在学习中。

You can do it using toString() and RegExp without any loops and streams:您可以使用 toString() 和 RegExp 来完成它,而无需任何循环和流:

List<Character> list = Arrays.asList('a', 'b', 'c'); String s = list.toString().replaceAll("[,\\s\\[\\]]", "");

Using join of a Joiner class:使用Joiner join的连接:

// create character list and initialize 
List<Character> arr = Arrays.asList('a', 'b', 'c');   
String str = Joiner.on("").join(arr);
System.out.println(str);

Use toString then remove , and spaces使用toString然后删除, and spaces

import com.google.common.base.Joiner; 

....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o'); 
// remove [] and spaces 
String str = arr.toString() 
          .substring(1, 3 * str.size() - 1) //3 bcs of commas ,
          .replaceAll(", ", ""); 
System.out.println(str);

Or by using streams:或者通过使用流:

import java.util.stream.Collectors; 
...
// using collect and joining() method 
String str =  arr.stream().map(String::valueOf).collect(Collectors.joining()); 

Assuming you have a following list:假设您有以下列表:

final ArrayList<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');

This will yield hello (I am using org.apache.commons.lang.ArrayUtils helper class):这将产生hello (我正在使用org.apache.commons.lang.ArrayUtils辅助类):

final Character[] charactersArray =
    charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));

a tiny complement to @waggledans 's answer对@waggledans 的回答的一个小小的补充

a) List of Character objects to String: a) 字符串的字符对象列表:

String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());

which e->e.toString() can be replaced by Object::toString其中e->e.toString()可以替换为Object::toString

String str = chars.stream().map(Object::toString).collect(Collectors.joining());

Easiest is to loop through.最简单的就是循环。

List<String> strings = new ArrayList<String>();

// populate strings

StringBuilder builder = new StringBuilder();

for(String string : strings) {
    builder.append(string).append(',');
}

if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}

System.out.println(builder);

Many solutions available.许多解决方案可用。 You can iterate over the chars and append to a StringBuilder, then when finished appending, call.toString on the StringBuilder.您可以将字符和 append 迭代到 StringBuilder,然后在完成附加后,在 StringBuilder 上调用.toString。

Or use something like commons-lang StringUtils.join from the apache commons-lang project.或者使用 apache commons-lang 项目中的 commons-lang StringUtils.join 之类的东西。

I consider this an easy and smart way我认为这是一种简单而聪明的方法

 // given list containing the chars
 List<Character> arr = Arrays.asList('a', 'b', 'c'); 

// convert to string.
String str = arr.toString(); // result is "[abc]"

// get rid of the start and the end char i.e '[' & ']'
arr = arr.substring(1, tmpArr.length()-1);  //result is "abc"

I would say:我会说:

public String arayListToString(ArrayList arrayList){

StringBuffer b = new StringBuffer();

for(String s : arrayList){
   b.append(s);
   b.append(",");
}

return b.toString();
}
 private void countChar() throws IOException {
    HashMap hashMap = new HashMap();
    List list = new ArrayList();
    list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
    list.stream().forEach(e -> {
        hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
        hashMap.computeIfAbsent(e, (V) -> 1);
    });

    System.out.println(hashMap);

}

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

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