Java 8 has introduced java.util.Optional class to find a value present or absent. Normally Java developers do “not null” check to identify whether the Object is null or to be used further for business logic. In a Enterprise application, lot of null checks present as each meaning object is checked, which makes the code messy. … Continue reading “Optional Keyword – Java 8”
Category: Java 8
Streams
1.Overview Streams are introduced in Java in Stream API to handle the operations on the list of elements in functional programming approach. Using Streams we can do multiple operations on the list of elements. We can do filtering(Filter) or ordering (Map) etc., on the list of elements/collections in the stream. Second is we can do … Continue reading “Streams”
forEach Expression
Starting Java 8, a new method forEach is introduced to iterate the elements. This forEach(Consumer<? super T> action) method is created in the following interfaces in java. java.lang.Iterable java.util.Stream This method performs a user given action on each element. In the below example, we can iterate a list of collections with forEach defining a condition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.ArrayList; import java.util.List; public class ForEachExample { public static void main(String args[]) { List numberList = new ArrayList(); numberList.add(1); numberList.add(2); numberList.add(3); numberList.add(4); numberList.add(5); numberList.add(6); numberList.add(7); numberList.add(8); System.out.println("All Numbers"); numberList.forEach((numValue)->{ System.out.println(""+numValue); }); System.out.println("Even Numbers"); numberList.forEach((numValue)->{ if(numValue%2==0) { System.out.println(""+numValue); } }); System.out.println("Stream Filter - Odd Numbers"); numberList.stream() .filter(numValue->(numValue%2==1)) .forEach(System.out::println); } } |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
All Numbers 1 2 3 4 5 6 7 8 Even Numbers 2 4 6 8 Stream Filter - Odd Numbers 1 3 5 7 |
Lambda Expressions
Lambda expression is a Java 8 feature, which helps the developer to simplify syntax of anonymous interface implementation whenever required. Interface is defined anonymously in earlier Java Implementation in the below old syntax., which is very much reduced in Java 8 lambda implementation, comparison of the below example provide a clear view of Lambda expression. … Continue reading “Lambda Expressions”