Loading...
Monday, September 10, 2018

Java 10 set with local variable Var and Different ways to iterate


Java10SetWithLocalVar.java
 package com.java9r;

import java.util.HashSet;

public class Java10SetWithLocalVar {

public static void main(String[] args) {
var products = new HashSet<>();
products.add("product 1");
products.add("product 2");
products.add("product 3");
products.add("product 4");
products.add("product 5");
products.add("product 6");

System.out.println("Iterate list using Enhanced for loop");
System.out.println("======================================");
for (var product : products) {
System.out.println("Name: " + product);
}

System.out.println("Iterate list using Stream API");
System.out.println("======================================");
products.forEach((product) -> {
System.out.println("Name: " + product);

});

System.out.println("Iterate list using for loop");
System.out.println("======================================");
// for(Iterator<String> product = products.iterator();it.hasNext();) {
for (var product = products.iterator(); product.hasNext();) {

System.out.println("Name : " + product.next());
}

System.out.println("Iterate list using while loop");
System.out.println("======================================");
// Iterator<String> product = products.iterator();
var product = products.iterator();
while (product.hasNext()) {

System.out.println("Name : " + product.next());
}

System.out.println("Iterate list using streaming example method reference");
System.out.println("======================================");

products.stream().forEach((name) -> System.out.println(name));

}

}


Output
 Iterate list using Enhanced for loop
======================================
Name: product 5
Name: product 6
Name: product 3
Name: product 4
Name: product 1
Name: product 2
Iterate list using Stream API
======================================
Name: product 5
Name: product 6
Name: product 3
Name: product 4
Name: product 1
Name: product 2
Iterate list using for loop
======================================
Name : product 5
Name : product 6
Name : product 3
Name : product 4
Name : product 1
Name : product 2
Iterate list using while loop
======================================
Name : product 5
Name : product 6
Name : product 3
Name : product 4
Name : product 1
Name : product 2
Iterate list using streaming example method reference
======================================
product 5
product 6
product 3
product 4
product 1
product 2

0 comments:

Post a Comment

 
TOP