Click here to watch in Youtube :
https://www.youtube.com/watch?v=Xv5j2bgX-B4&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java Tutorial: Lambda expression in java | Java Lambda expressions[forEach method of List] |
import java.util.ArrayList;
import java.util.List;
public class LambdaDemo1
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<>();
nameList.add("Peter");
nameList.add("John");
nameList.add("Juli");
nameList.add("Stephan");
/*
* Before Java 8, Normal way to loop a list.
*/
for (String name : nameList)
{
System.out.println(name);
}
System.out.println("------------------------------------");
/*
* In Java 8, we can loop a List with forEach + lambda
* expression or method reference.
*/
nameList.forEach(name -> System.out.println(name));
}
}
OutputPeter
John
Juli
Stephan
------------------------------------
Peter
John
Juli
Stephan
LambdaDemo2.javaimport java.util.ArrayList;
import java.util.List;
public class LambdaDemo2
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<>();
nameList.add("Peter");
nameList.add("John");
nameList.add("Juli");
nameList.add("Stephan");
/*
* In Java 8, we can loop a List with forEach + lambda
* expression or method reference.
*/
nameList.forEach(name -> {
if ("John".equals(name))
{
System.out.println("Hello " + name);
}
});
}
}
OutputHello John
LambdaDemo3.javaimport java.util.ArrayList;
import java.util.List;
public class LambdaDemo3
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<>();
nameList.add("Peter");
nameList.add("John");
nameList.add("Juli");
nameList.add("Stephan");
/*
* In Java 8, we can loop a List with forEach + lambda
* expression or method reference.
*/
//method reference
nameList.forEach(System.out::println);
}
}
OutputPeter
John
Juli
Stephan
LambdaDemo4.javaimport java.util.ArrayList;
import java.util.List;
public class LambdaDemo4
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<>();
nameList.add("Peter");
nameList.add("John");
nameList.add("Juli");
nameList.add("Stephan");
/*
* In Java 8, we can loop a List with forEach + lambda
* expression or method reference.
*/
//Stream and filter
nameList.stream()
.filter(name->name.contains("Juli"))
.forEach(System.out::println);
}
}
OutputJuli
Refer https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/LambdaDemo_list_foreach_app.zip?attredirects=0&d=1
No comments:
Post a Comment