Java collections convert a string to a list of characters

前端 未结 10 1989
礼貌的吻别
礼貌的吻别 2020-12-02 12:51

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

        
10条回答
  •  攒了一身酷
    2020-12-02 13:24

    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 list = new ArrayList();
    Set unique = new HashSet();
    for(char c : "abc".toCharArray()) {
        list.add(c);
        unique.add(c);
    }
    

    Here is an Arrays.asList like wrapper for strings:

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

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

    public List asList(final char[] string) {
        return new AbstractList() {
           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.

    The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).

提交回复
热议问题