java - Operation on ArrayList elements without using any loop -


i writing 1 java program in don't want use loop array list elements. sure below program print output 0 n without using loop because arraylist inherits tostring() method loop in abstractcollection.

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 want put calculations using each element in array list without loop.like 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 = arr.iterator();         while(it.hasnext()){             integer element = it.next();             if(element%i==0)             count++;         }     }     system.out.println(count); } } 

now if use program give me approximately o(n*m) solution don't want. there way can access elements in array list without using loop ?

java 8 can make code simpler using intstream.rangeclosed, there little can avoid having o(n*m) solution without devising smarter algorithm.

long count = intstream.rangeclosed(0, n)                       .maptolong(element -> intstream.rangeclosed(2, m)                           .filter(i -> element % == 0)                           .count())                       .sum(); system.out.println(count); 

previous java 8, equivalent code like:

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

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -