Introduction to Lambda Expressions and Streams in Java

Introduction to Lambda Expressions

@FunctionalInterface
interface Age {
int x = 21;
void getAge();
}
class Test{
public static void main(String args[]){
Age age = new Age(
@Override
public void getAge()
{
// some operation
System.out.print("inside Age function");
});
}
class Test {
public static void main(String args[])
{
Age age = () -> System.out.println("Inside age function");
// This will print "inside age function"
age.getAge(5);
}
}

Basic Syntax of lambda Expression

parameter -> expression
(parameter1, parameter2) -> expression
(parameter1, parameter2) -> { code block }
  1. Using Consumer interface in java
import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
public class Main {
public static void main(String[] args) {
Runnable r2=()->{
System.out.println("Thread2 is running...");};
Thread t2=new Thread(r2);
t2.start();
}
}
@FunctionalInterface  
interface Sayable{
String say(String message);
}

public class Main{
public static void main(String[] args) {

Sayable person = (message)-> {
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};

System.out.println(person.say("time is precious."));
}
}

Introduction to Streams

List<Employee> employeeList = new ArrayList<>();
Stream<Employee> emp = employeeList.stream()
  1. Intermediate operations: These methods do not produce any results. They usually accept functional interfaces as parameters and always return a new stream.
  2. Terminal operations: These methods produce some results, e.g., count(), collect() etc.

Examples of Intermediate operations

  1. map: The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream()
.map(x->x*x)
.collect(Collectors.toList());
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream()
.filter(s->s.startsWith("S"))
.collect(Collectors.toList());
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted()
.collect(Collectors.toList());

Examples of Terminal operations

  1. collect: The collect method is used to return the result of the intermediate operations performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream()
.map(x>x*x)
.collect(Collectors.toSet());
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x)
.forEach(y->System.out.println(y));
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x)
.filter(x->x>4).count();

Sample uses of streams

  1. Count occurrence of given character ‘ch’ in string
public static long count(String s, char ch){
return s.chars()
.filter(c -> c == ch)
.count();
}
List<String> nameList = Arrays.asList("Jayesh", "Dany", "Khyati", "Hello", "Mango");
nameList.stream()
.map(String::toUpperCase)
.forEach(System.out::println);

Conclusion

References

  1. https://www.geeksforgeeks.org/lambda-expressions-java-8/
  2. https://www.geeksforgeeks.org/stream-in-java/
  3. http://tutorials.jenkov.com/java/lambda-expressions.html
  4. https://www.baeldung.com/java-8-streams

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Summary of the Book “Infrastructure As Code” by Kief Morris

Why HTTP/3?

The making of OJOS

Is Your Organization Optimizing IT Service Management? Here is How an ITSM Tool Can help?

5 functions of an ITSM tool

September Development Update

Setup a 3D and Video Studio on Ubuntu Linux for Free

Making Minecraft Mining less monotonous with python

Windows 10 start menu not working problem Fixed

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shivani Bagalwadi

Shivani Bagalwadi

Software Engineer

More from Medium

Numbering System edge cases of java

Multithreading in Java

Staircase | HackerRank Problem | Java Solution