Print Square in Java Using Lambda or Stream API

Creates an IntStream using the iterate method. The method prints to the console the
first num squares. For instance, if num = 4, then your method would output 1, 4, 9, 16. Note:
You will need to come up with a function to be used in the second argument of iterate .


public class Test {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

   System.out.println(printSSquare(5));
  //printSSquare(5).forEach(System.out::print);
    printUsingSream(5);
    
    
 }
 
 //Using java 8
 private static void printUsingSream(int ns) {
  // TODO Auto-generated method stub
  IntStream intS=IntStream.iterate(1, n->n+1).map(i->i*i).limit(ns);
  intS.forEach(System.out::println);
  
  
 }

    // Old techniques , Previous java 8
 private static List<Integer> printSSquare(int i) {
  
  List<Integer> test= new ArrayList<>();
  // TODO Auto-generated method stub
  for (int j = 1; j <= i; j++) {
   test.add(j*j);
   
  }
  return test;
 }

}




Output :

[1, 4, 9, 16, 25]
1
4
9
16
25

Happy Coding !!!

0 comments:

Post a Comment