【问题标题】:Can only iterate over an array or an instance of java.lang.Iterable?只能遍历数组或 java.lang.Iterable 的实例吗?
【发布时间】:2017-09-05 19:48:28
【问题描述】:

我尝试 forEach 一个二维列表,将一个 int [] 数组放入 lambda。编译器报错“只能遍历数组或 java.lang.Iterable 的实例”

    List<int []> list2d = new ArrayList<>();
    list2d.add(new int[] {1,3,5,7});
    list2d.add(new int[] {2,4,6,8});

    list.forEach((array)-> {        */// why here array can't be iterated?*
        for(int num: array) {
            System.out.println(num);
        }
    });

【问题讨论】:

  • 澄清一下,真的是list.forEach,而不是list2d.forEach?如果是这样,list 是什么? (我怀疑您有两个名称相似的变量,并且使用了错误的变量。)
  • 适用于list2d.forEach。投票结束为错字。

标签: java foreach


【解决方案1】:

如果我对您的理解正确,您希望遍历数组元素中的元素。您可以通过以下方式实现此目的:

list2d.stream()
      .flatMapToInt( Arrays::stream )
      .forEach( System.out::println );

【讨论】:

    【解决方案2】:

    我在我的电脑上试过了,它可以工作,但你需要使用正确的变量:

    list.forEach((array)-> {        // why here array can't be iterated?
        for(int num: array) {
            System.out.println(num);
        }
    });
    

    您必须迭代 list2d 而不是列表,不是吗? 另外,请记住 java 中的 cmets 在 /* */ 之间或 // if 之后是一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多