【问题标题】:Java collections convert a string to a list of charactersJava 集合将字符串转换为字符列表
【发布时间】:2011-06-12 02:39:01
【问题描述】:

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

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

【问题讨论】:

    标签: java string collections


    【解决方案1】:

    我想在 Java8 中你可以使用流。 角色对象列表:

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

    同样可以得到set:

    Set<Character> charsSet = str.chars()
        .mapToObj(e->(char)e).collect(Collectors.toSet());
    

    【讨论】:

    • 导入java.util.stream.Collectors 是此sn-p 工作所必需的。
    • chars 方法是在 Java 9 中引入的 - 它在 Java 8 中不存在。
    • @SteveChambers 它确实存在于 Java 8 中的 CharSequencedocs.oracle.com/javase/8/docs/api/java/lang/…
    • @Unmitigated Ah 好点。
    【解决方案2】:

    您将不得不使用循环,或者创建一个像 Arrays.asList 这样的集合包装器,它适用于原始 char 数组(或直接适用于字符串)。

    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 的字符串包装器:

    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[] 一起使用:

    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;
           }
        };
    }
    

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

    Guava library 包含similar List wrapper methods for several primitive array classes,如Chars.asList,以及Lists.charactersOf(String) 中的字符串包装器。

    【讨论】:

      【解决方案3】:

      一些第三方库解决了原始数组与其对应包装类型的集合之间缺乏转换的好方法。番石榴,很常见的一种,has a convenience method to do the conversion

      List<Character> characterList = Chars.asList("abc".toCharArray());
      Set<Character> characterSet = new HashSet<Character>(characterList);
      

      【讨论】:

      • 看起来我在这里重新发明了轮子......我想Chars.asList 对我的答案中的asList 方法做了什么。
      • 在番石榴中还有Lists.charactersOf("abc"),它有点短,不会让我们打电话给toCharArray()
      【解决方案4】:

      使用 Java 8 Stream

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

      细分:

      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>
      

      (我完全不知道为什么String#chars() 返回IntStream。)

      【解决方案5】:

      最直接的方法是使用for 循环将元素添加到新的List

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

      同样,对于Set

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

      【讨论】:

        【解决方案6】:
        List<String> result = Arrays.asList("abc".split(""));
        

        【讨论】:

          【解决方案7】:

          创建一个空的Character列表,然后循环获取数组中的每个字符,并一个一个的放入列表中。

          List<Character> characterList = new ArrayList<Character>();
          char arrayChar[] = abc.toCharArray();
          for (char aChar : arrayChar) 
          {
              characterList.add(aChar); //  autoboxing 
          }
          

          【讨论】:

            【解决方案8】:

            如果你使用Eclipse Collections,你可以在不装箱的情况下做到这一点:

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

            因为CharAdapterImmutableCharList,所以调用collect 将返回ImmutableList

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

            如果您想返回已装箱的 ListSetBagCharacter,则可以使用以下方法:

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

            注意:我是 Eclipse Collections 的提交者。

            【讨论】:

              【解决方案9】:

              IntStream 可用于访问每个字符并将它们添加到列表中。

              String str = "abc";
              List<Character> charList = new ArrayList<>();
              IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));
              

              【讨论】:

                【解决方案10】:

                使用 Java 8 - 流函数:

                将字符串转换为字符列表:

                ArrayList<Character> characterList =  givenStringVariable
                                                                         .chars()
                                                                         .mapToObj(c-> (char)c)
                                                                         .collect(collectors.toList());
                

                将字符列表转换为字符串:

                 String givenStringVariable =  characterList
                                                            .stream()
                                                            .map(String::valueOf)
                                                            .collect(Collectors.joining())
                

                【讨论】:

                  【解决方案11】:

                  获取字符/字符串列表 -

                  List<String> stringsOfCharacters = string.chars().
                                                     mapToObj(i -> (char)i).
                                                     map(c -> c.toString()).
                                                     collect(Collectors.toList());
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-05-02
                    • 2018-02-19
                    相关资源
                    最近更新 更多