【问题标题】:Convert List<String> to List<Integer> directly将 List<String> 直接转换为 List<Integer>
【发布时间】:2012-05-29 05:18:05
【问题描述】:

解析我的文件“s”后包含AttributeGet:1,16,10106,10111

所以我需要获取attributeIDGet List中冒号后的所有数字。我知道有几种方法可以做到这一点。但是有什么方法可以直接将List&lt;String&gt; 转换为List&lt;Integer&gt; 由于下面的代码抱怨类型不匹配,所以我尝试执行 Integer.parseInt,但我想这不适用于 List。这里 s 是字符串。

private static List<Integer> attributeIDGet = new ArrayList<Integer>();

if(s.contains("AttributeGet:")) {
    attributeIDGet = Arrays.asList(s.split(":")[1].split(","));
}

【问题讨论】:

    标签: java list collections arraylist


    【解决方案1】:

    不,您必须遍历每个元素:

    for(String number : numbers) {
       numberList.add(Integer.parseInt(number)); 
    }
    

    发生这种情况的原因是没有直接的方法可以将一种类型的列表转换为任何其他类型。有些转换是不可能的,或者需要以特定的方式完成。本质上,转换取决于所涉及的对象和转换的上下文,因此没有“一刀切”的解决方案。例如,如果您有一个Car 对象和一个Person 对象怎么办。您不能直接将 List&lt;Car&gt; 转换为 List&lt;Person&gt;,因为它没有任何意义。

    【讨论】:

      【解决方案2】:

      不行,你需要遍历数组

      for(String s : strList) intList.add(Integer.valueOf(s));
      

      【讨论】:

      • 您所写的内容实际上是对值进行循环。但它仍然是一个优雅的解决方案。只是为了补充一点。使用新的 lambda 方法。 intList.addAll(strList.stream().map(Integer::valueOf).collect(Collectors.toList()));
      • 甚至 strList.foreach(s->intList.add(Integer.valueOf(s));
      • 您可以使用 Lambda 转换此列表
      【解决方案3】:

      不,没有办法(据我所知)在 Java 中这样做。

      基本上,您必须将每个条目从字符串转换为整数。

      您正在寻找的东西可以用一种更实用的语言来实现,您可以在其中传递一个转换函数并将其应用于列表的每个元素......但这是不可能的(它仍然适用于每个元素在列表中)。

      矫枉过正:

      但是,您可以使用来自 Google Guava (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html) 的函数来模拟更实用的方法,如果那是你要找的。​​p>

      如果您担心对列表进行两次迭代,那么不要使用拆分器,而是在添加到列表之前将每个整数标记转换为整数。

      【讨论】:

      • 在这里使用Function 太过分了。
      • 我知道,它不会在效率方面取得任何成果,而且它矫枉过正,我只是想指出它是一种模拟更“功能性”的方式方法。不幸的是,您只是在模仿这种行为,并且通常以臃肿的代码告终。
      【解决方案4】:

      如果您使用Google Guava library,您可以这样做,请参阅Lists#transform

          String s = "AttributeGet:1,16,10106,10111";
      
      
          List<Integer> attributeIDGet = new ArrayList<Integer>();
      
          if(s.contains("AttributeGet:")) {
              List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
              attributeIDGet =
              Lists.transform(attributeIDGetS, new Function<String, Integer>() {
                  public Integer apply(String e) {
                      return Integer.parseInt(e);
                  };
              });
          }
      

      是的,同意上面的答案,就是它很臃肿,但很时尚。但这只是另一种方式。

      【讨论】:

        【解决方案5】:

        这是另一个展示番石榴力量的例子。虽然,这不是我编写代码的方式,但我想将它们打包在一起,以展示 Guava 为 Java 提供了什么样的函数式编程。

        Function<String, Integer> strToInt=new Function<String, Integer>() {
            public Integer apply(String e) {
                 return Integer.parseInt(e);
            }
        };
        String s = "AttributeGet:1,16,10106,10111";
        
        List<Integer> attributeIDGet =(s.contains("AttributeGet:"))?
          FluentIterable
           .from(Iterables.skip(Splitter.on(CharMatcher.anyOf(";,")).split(s)), 1))
           .transform(strToInt)
           .toImmutableList():
           new ArrayList<Integer>();
        

        【讨论】:

          【解决方案6】:

          如果您被允许使用 Java 8 中的 lambda,则可以使用以下代码示例。

          final String text = "1:2:3:4:5";
          final List<Integer> list = Arrays.asList(text.split(":")).stream()
            .map(s -> Integer.parseInt(s))
            .collect(Collectors.toList());
          System.out.println(list);
          

          不使用外部库。普通新Java!

          【讨论】:

          • 我收到此语法错误:类型不匹配:无法在 map 函数中从 String 转换为 int。你能帮我解决这个问题吗
          • @SonalMaheshwari 您使用的是什么版本的 Java(以及在什么环境中)?我在 Mac OS X 上使用 1.8.0_05。您能否提供一个 SSCCE(在 pastebin 或同等产品上)?
          【解决方案7】:

          为什么不使用流将字符串列表转换为整数列表? 如下所示

          List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
                      "50", "60", "70"));
          List<Integer> integerList = stringList.stream()
                      .map(Integer::valueOf).collect(Collectors.toList());
          

          完整的操作可能是这样的

          String s = "AttributeGet:1,16,10106,10111";
          List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
              Arrays.asList(s.replace("AttributeGet:", "").split(","))
              .stream().map(Integer::valueOf).collect(Collectors.toList())
              : new ArrayList<Integer>();
          

          【讨论】:

            【解决方案8】:

            Guava Converters 做到这一点。

            import com.google.common.base.Splitter;
            import com.google.common.primitives.Longs;
            
            final Iterable<Long> longIds = 
                Longs.stringConverter().convertAll(
                    Splitter.on(',').trimResults().omitEmptyStrings()
                        .splitToList("1,2,3"));
            

            【讨论】:

              【解决方案9】:

              使用 lambda:

              strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());

              【讨论】:

                【解决方案10】:

                您可以使用 Java 8 的 Lambda 函数来实现此目的而无需循环

                    String string = "1, 2, 3, 4";
                    List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
                

                【讨论】:

                  【解决方案11】:

                  使用 Java8:

                  stringList.stream().map(Integer::parseInt).collect(Collectors.toList());
                  

                  【讨论】:

                  • 如果将 StringList 发送到方法 (List) 则不能。我认为需要创建新的 List 和循环
                  • @Jagadeesh:如果字符串不是整数,则 Integer::parseInt 会抛出 NumberFormatException。您可以使用例如来自 Apache Commons 的 StringUtils::isNumeric 过滤掉非整数元素。
                  【解决方案12】:

                  使用流和 Lambda:

                  newIntegerlist = listName.stream().map(x-> 
                      Integer.valueOf(x)).collect(Collectors.toList());
                  

                  上面这行代码会将List&lt;String&gt;类型的List转换成List&lt;Integer&gt;

                  希望对你有帮助。

                  【讨论】:

                    【解决方案13】:

                    使用 Guava 变换方法如下,

                    List intList = Lists.transform(stringList, Integer::parseInt);

                    【讨论】:

                      【解决方案14】:

                      导入 java.util.Arrays; 导入 java.util.Scanner;

                      公共类 reto1 {

                      public static void main(String[] args) {
                          Scanner input = new Scanner(System.in);
                              double suma = 0, promedio = 0;
                              String IRCA = "";
                              int long_vector = Integer.parseInt(input.nextLine());    
                              int[] Lista_Entero = new int[long_vector];       // INSTANCE INTEGER LIST
                              String[] lista_string = new String[long_vector]; // INSTANCE STRING LIST
                              Double[] lista_double = new Double[long_vector];
                              lista_string = input.nextLine().split(" ");     //  INPUT STRING LIST
                          input.close();
                      
                          for (int i = 0; i < long_vector; i++) {
                              Lista_Entero[i] = Integer.parseInt(lista_string[i]); // CONVERT INDEX TO INDEX FROM STRING UNTIL INTEGER AND ASSIGNED TO NEW INTEGER LIST
                              suma = suma + Lista_Entero[i];
                          }
                      

                      【讨论】:

                        猜你喜欢
                        • 2010-09-06
                        • 2022-09-30
                        • 2013-08-03
                        • 2023-03-26
                        • 1970-01-01
                        • 2020-02-17
                        • 2015-11-03
                        相关资源
                        最近更新 更多