Java collections convert a string to a list of characters

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

    Use a Java 8 Stream.

    myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
    

    Breakdown:

    myString
        .chars() // Convert to an IntStream
        .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
        .collect(Collectors.toList()); // Collect in a List<Character>
    

    (I have absolutely no idea why String#chars() returns an IntStream.)

    0 讨论(0)
  • 2020-12-02 13:33

    Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.

    List<Character> characterList = new ArrayList<Character>();
    char arrayChar[] = abc.toCharArray();
    for (char aChar : arrayChar) 
    {
        characterList.add(aChar); //  autoboxing 
    }
    
    0 讨论(0)
  • 2020-12-02 13:39

    The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

    List<Character> characterList = Chars.asList("abc".toCharArray());
    Set<Character> characterSet = new HashSet<Character>(characterList);
    
    0 讨论(0)
  • 2020-12-02 13:44

    In Java8 you can use streams I suppose. List of Character objects:

    List<Character> chars = str.chars()
        .mapToObj(e->(char)e).collect(Collectors.toList());
    

    And set could be obtained in a similar way:

    Set<Character> charsSet = str.chars()
        .mapToObj(e->(char)e).collect(Collectors.toSet());
    
    0 讨论(0)
提交回复
热议问题