Java collections convert a string to a list of characters

前端 未结 10 2000
礼貌的吻别
礼貌的吻别 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:31

    You can do this without boxing if you use Eclipse Collections:

    CharAdapter abc = Strings.asChars("abc");
    CharList list = abc.toList();
    CharSet set = abc.toSet();
    CharBag bag = abc.toBag();
    

    Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.

    ImmutableList immutableList = abc.collect(Character::valueOf);
    

    If you want to return a boxed List, Set or Bag of Character, the following will work:

    LazyIterable lazyIterable = abc.asLazy().collect(Character::valueOf);
    List list = lazyIterable.toList();
    Set set = lazyIterable.toSet();
    Bag set = lazyIterable.toBag();
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题