【问题标题】:How to convert contents of String ArrayList to char ArrayList如何将 String ArrayList 的内容转换为 char ArrayList
【发布时间】:2015-07-06 12:35:35
【问题描述】:

我目前有一个字符串数组列表,其内容为 [a, b, c, d, e...] 等等。但是,我需要一个基于字符的数组列表(ArrayList 名称)。我将如何循环遍历我的 String 数组列表并将其元素转换为 char 以附加到 char 数组列表?

将包含数字 [1,2,3,4...] 的字符串数组列表转换为整数数组列表也是如此。我将如何循环、转换类型并将其添加到新的数组列表中?

【问题讨论】:

    标签: java string arraylist char


    【解决方案1】:

    对于第一个问题,只需使用 for 循环并使用字符串的 char charAt(0) 方法

    List<String> arrayList;
    List<Character> newArrayList = new ArrayList<>();
    
    for( int i = 0; i < arrayList.size(); i++ ){
        String string = arrayList.at(i);
        newArrayList.add( string.charAt(0) ); // 0 becouse each string have only 1 char
    }
    

    第二个你可以使用Intenger.parseint

    List<String> arrayList;
    List<int> newArrayList = new ArrayList<>();
    
    for( int i = 0; i < arrayList.size(); i++ )
    {
        String string = arrayList.at(i);
        newArrayList.add( Intenget.parseInt(string) );
    }
    

    【讨论】:

      【解决方案2】:

      正如你所说 - 你必须遍历 ArrayList:

      List<String> stringList = ...;
      List<Character> charList = new ArrayList<>(old.size());
      
      // assuming all the strings in old have one character, 
      // as per the example in the question 
      for (String s : stringList) {
          charList.add(s.charAt(0));
      }
      

      编辑:
      您没有指定您使用的是哪个 Java 版本,但在 Java 8 中,这可以使用stream() 方法更优雅地完成很多

      List<Character> charList = 
          stringList.stream().map(s -> s.charAt(0)).collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 2015-08-06
        • 2011-08-20
        • 1970-01-01
        • 2012-06-06
        • 2017-11-09
        相关资源
        最近更新 更多