【问题标题】:convert List of Integers to Integer array in java [duplicate]在java中将整数列表转换为整数数组[重复]
【发布时间】:2017-06-02 14:24:03
【问题描述】:

我有那个方法:

 public void checkCategories(Integer... indices) {
    .....
  } 

这个方法的输入是Integer列表。

我的问题是如何将整数列表的列表转换为整数数组以在该方法中传递?

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以将列表转换为ArrayList,如下所示:

    userList = new ArrayList<Integer>();
    

    然后,您可以将该列表转换为 Array 使用

    int[] userArray = userList.toArray(new int[userList.size()]);
    

    【讨论】:

      【解决方案2】:

      可以通过toArray()方法将List转为数组

      List<Integer> integerList = new ArrayList<Integer>();
      
      Integer[] flattened = new Integer[integerList.size()];
      integerList.toArray(flattened);
      
      checkCategories(flattened);
      

      【讨论】:

        【解决方案3】:

        如果您需要将列表扁平化为数组,您可以尝试类似的方法:

        public static void main(String [] args) {
            List<List<Integer>> integers = Lists.newArrayList(
                    Lists.newArrayList(1, 2, 3, 4),
                    Lists.newArrayList(5, 3, 6, 7)
            );
        
            Integer[] flattened = integers.stream()
                    .flatMap(Collection::stream)
                    .toArray(Integer[]::new);
        
            checkCategories(flattened);
        }
        
        public static void checkCategories(Integer... indices) {
            for (Integer i : indices) {
                System.out.println(i);
            }
        }
        

        打印出来:

        1
        2
        3
        4
        5
        3
        6
        7
        

        【讨论】:

          猜你喜欢
          • 2023-03-13
          • 2021-10-14
          • 1970-01-01
          • 2016-02-04
          • 1970-01-01
          • 1970-01-01
          • 2019-02-08
          • 2015-03-12
          • 1970-01-01
          相关资源
          最近更新 更多