【问题标题】:Convert Integer List to int array [duplicate]将整数列表转换为整数数组[重复]
【发布时间】:2023-03-13 14:35:01
【问题描述】:

有没有办法将整数列表转换为整数数组(不是整数)。像 List 到 int [] 之类的东西?无需遍历列表并手动将整数转换为整数。

【问题讨论】:

  • 这里的循环有什么问题?

标签: java core


【解决方案1】:

您可以使用toArray 从apache commons 中获取IntegersArrayUtils 的数组,以将其转换为int[]


List<Integer> integerList = new ArrayList<Integer>();
Integer[] integerArray = integerList.toArray(new Integer[0]);
int[] intArray = ArrayUtils.toPrimitive(integerArray);

资源:

关于同一主题:

【讨论】:

  • +1,即将发布相同的内容。 :-)
  • 有一个错字,应该是ArrayUtils
  • 为了安全起见,您需要在调用toArray()之前从列表中删除所有空元素
【解决方案2】:

我确信您可以在第三方库中找到一些东西,但我不相信 Java 标准库中内置了任何东西。

我建议你只写一个实用函数来完成它,除非你需要很多类似的功能(在这种情况下,值得寻找相关的 3rd 方库)。请注意,您需要弄清楚如何处理列表中的空引用,这显然无法在 int 数组中准确表示。

【讨论】:

    【解决方案3】:

    没有:)

    您需要遍历列表。应该不会太痛。

    【讨论】:

      【解决方案4】:

      这是一个实用方法,可将整数集合转换为整数数组。如果输入为 null,则返回 null。如果输入包含任何空值,则会创建一个防御性副本,从中剥离所有空值。原始集合保持不变。

      public static int[] toIntArray(final Collection<Integer> data){
          int[] result;
          // null result for null input
          if(data == null){
              result = null;
          // empty array for empty collection
          } else if(data.isEmpty()){
              result = new int[0];
          } else{
              final Collection<Integer> effective;
              // if data contains null make defensive copy
              // and remove null values
              if(data.contains(null)){
                  effective = new ArrayList<Integer>(data);
                  while(effective.remove(null)){}
              // otherwise use original collection
              }else{
                  effective = data;
              }
              result = new int[effective.size()];
              int offset = 0;
              // store values
              for(final Integer i : effective){
                  result[offset++] = i.intValue();
              }
          }
          return result;
      }
      

      更新:Guava 有一个用于此功能的单行代码:

      int[] array = Ints.toArray(data);
      

      参考:

      【讨论】:

        【解决方案5】:
            List<Integer>  listInt = new ArrayList<Integer>();
        
            StringBuffer strBuffer = new StringBuffer();
        
            for(Object o:listInt){
                strBuffer.append(o);
            }
        
            int [] arrayInt = new int[]{Integer.parseInt(strBuffer.toString())};
        

        我认为这应该可以解决您的问题

        【讨论】:

          猜你喜欢
          • 2017-06-02
          • 2021-10-14
          • 1970-01-01
          • 2016-02-04
          • 2015-03-12
          • 1970-01-01
          • 1970-01-01
          • 2012-08-28
          • 2013-04-27
          相关资源
          最近更新 更多