Java 集合将字符串转换为字符列表 [英] Java collections convert a string to a list of characters

查看:31
本文介绍了Java 集合将字符串转换为字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将包含 abc 的字符串转换为字符列表和字符哈希集.我怎样才能在 Java 中做到这一点?

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?

List<Character> charList = new ArrayList<Character>("abc".toCharArray());

推荐答案

你必须要么使用循环,要么创建一个像 Arrays.asList 这样处理原始字符数组(或直接在字符串上).

You will have to either use a loop, or create a collection wrapper like Arrays.asList which works on primitive char arrays (or directly on strings).

List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
    list.add(c);
    unique.add(c);
}

这是一个 Arrays.asList 类似字符串的包装器:

Here is an Arrays.asList like wrapper for strings:

public List<Character> asList(final String string) {
    return new AbstractList<Character>() {
       public int size() { return string.length(); }
       public Character get(int index) { return string.charAt(index); }
    };
}

不过,这是一个不可变的列表.如果您想要一个可变列表,请将其与 char[] 一起使用:

This one is an immutable list, though. If you want a mutable list, use this with a char[]:

public List<Character> asList(final char[] string) {
    return new AbstractList<Character>() {
       public int size() { return string.length; }
       public Character get(int index) { return string[index]; }
       public Character set(int index, Character newVal) {
          char old = string[index];
          string[index] = newVal;
          return old;
       }
    };
}

与此类似,您可以为其他原始类型实现此功能.请注意,通常不建议使用它,因为对于每次访问您会进行装箱和拆箱操作.

Analogous to this you can implement this for the other primitive types. Note that using this normally is not recommended, since for every access you would do a boxing and unboxing operation.

Guava 库 包含 几个原始数组类的类似列表包装方法,例如Chars.asList,和Lists.charactersOf(String).

这篇关于Java 集合将字符串转换为字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆