Java collections convert a string to a list of characters

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

    The most straightforward way is to use a for loop to add elements to a new List:

    String abc = "abc";
    List charList = new ArrayList();
    
    for (char c : abc.toCharArray()) {
      charList.add(c);
    }
    

    Similarly, for a Set:

    String abc = "abc";
    Set charSet = new HashSet();
    
    for (char c : abc.toCharArray()) {
      charSet.add(c);
    }
    

提交回复
热议问题