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 !!!

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete