简体   繁体   English

在不使用任何循环的情况下对ArrayList元素进行操作

[英]Operation on ArrayList elements without using any loop

I am writing one java program in which I don't want to use any loop for array list elements. 我正在编写一个Java程序,其中不想对数组列表元素使用任何循环。 Sure below program will print the output from 0 to n without using any loop because ArrayList inherits a toString() method with a loop in it from AbstractCollection. 当然,下面的程序将在不使用任何循环的情况下将输出从0打印到n,这是因为ArrayList从AbstractCollection继承了一个带有循环的toString()方法。

import java.util.*;
class withoutloop{
public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    ArrayList<Integer> arr = new ArrayList<>();
    int n = scan.nextInt();
    for(int i=0;i<=n;i++)
    arr.add(i);
    System.out.println(arr);
}
}

But I want to put some calculations using each element in array list without any loop.Like the below program 但是我想使用数组列表中的每个元素进行一些计算而没有任何循环,就像下面的程序

import java.util.*;
class withoutloop{
public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    ArrayList<Integer> arr = new ArrayList<>();
    int n = scan.nextInt();
    int m = scan.nextInt();
    int count = 0;
    for(int i=0;i<=n;i++)
    arr.add(i);
    for(int i=2;i<=m;i++){
    Iterator it = arr.iterator();
        while(it.hasNext()){
            Integer element = it.next();
            if(element%i==0)
            count++;
        }
    }
    System.out.println(count);
}
}

Now if I use this program this will give me approximately O(n*m) solution which I don't want. 现在,如果我使用该程序,它将为我提供大约不需要的O(n * m)解决方案。 Is there any way I can access all elements in array list without using any loop ? 有什么办法可以不使用任何循环就访问数组列表中的所有元素?

Java 8 can make your code simpler using IntStream.rangeClosed , but there is little you can do to avoid having an O(n*m) solution without devising a smarter algorithm. Java 8使用IntStream.rangeClosed可以使您的代码更简单,但是如果没有设计出更智能的算法,您几乎可以避免使用O(n * m)解决方案。

long count = IntStream.rangeClosed(0, n)
                      .mapToLong(element -> IntStream.rangeClosed(2, m)
                          .filter(i -> element % i == 0)
                          .count())
                      .sum();
System.out.println(count);

Previous to Java 8, the equivalent code would be something like: 在Java 8之前,等效代码如下所示:

long count = 0;
for (int element = 0; element <= n; element++) {
    for (int i = 2; i <= m; i++) {
        if (element % i == 0) {
            count++;
        }
    }
}
System.out.println(count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM