Introduction:
Java Streams are a powerful tool for performing complex data manipulations in a concise and readable way. In this article, we will discuss various operations that can be performed on Java streams with examples. We will cover both intermediate and terminal operations, and provide examples for each.
Intermediate Operations:
Intermediate operations are operations that transform a stream into another stream, allowing us to perform various operations on the data in the stream. Here are some examples of intermediate operations:
- map: The map method is used to transform each element in the stream by applying a given function to it. For example, let's say we have a list of numbers and we want to create a new list with the squares of those numbers. We can use the map method to achieve this as follows:
scssList<Integer> numbers = Arrays.asList(2,3,4,5);
List<Integer> squares = numbers.stream()
.map(x->x*x)
.collect(Collectors.toList());
- filter: The filter method is used to select elements from a stream based on a given predicate. For example, let's say we have a list of names and we want to create a new list with only the names that start with the letter "S". We can use the filter method to achieve this as follows:
rustList<String> names = Arrays.asList("Reflection","Collection","Stream");
List<String> result = names.stream()
.filter(s->s.startsWith("S"))
.collect(Collectors.toList());
- sorted: The sorted method is used to sort the elements of a stream. For example, let's say we have a list of names and we want to create a new list with the same names but sorted alphabetically. We can use the sorted method to achieve this as follows:
javascriptList<String> names = Arrays.asList("Reflection","Collection","Stream");
List<String> result = names.stream()
.sorted()
.collect(Collectors.toList());
Terminal Operations:
Terminal operations are operations that produce a result or side-effect from a stream. Here are some examples of terminal operations:
- collect: The collect method is used to produce a result from the intermediate operations performed on the stream. For example, let's say we have a list of numbers and we want to create a set with the squares of those numbers. We can use the collect method to achieve this as follows:
scssList<Integer> numbers = Arrays.asList(2,3,4,5,3);
Set<Integer> squares = numbers.stream()
.map(x->x*x)
.collect(Collectors.toSet());
- forEach: The forEach method is used to perform a side-effect on each element of the stream. For example, let's say we have a list of numbers and we want to print the squares of those numbers. We can use the forEach method to achieve this as follows:
scssList<Integer> numbers = Arrays.asList(2,3,4,5);
numbers.stream()
.map(x->x*x)
.forEach(y->System.out.println(y));
- reduce: The reduce method is used to reduce the elements of a stream to a single value. For example, let's say we have a list of numbers and we want to calculate the sum of all even numbers in the list. We can use the reduce method to achieve this as follows:
scssList<Integer> numbers = Arrays.asList(2,3,4,5);
int even = numbers.stream()
.filter(x->x%2==0)
.reduce(0,(ans,i)-> ans+i);
Examples: Let's go through some examples to demonstrate how Java Streams can be used in practice.
Example 1: Using Stream to find the longest string in an array. The reduce() method is used to accumulate the elements of a stream and return a single summary result. The BinaryOperator interface is used to define the computation performed by the reduce method.
// Java code to find the longest string // in array using Stream in Java import java.util.*;
class GfG { public static void main (String[] args) { String arr[] = {"a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg"};
scss// Find maximum length string
String res = Arrays.stream(arr)
.reduce((x, y) -> x.length() > y.length() ? x : y)
.get();
// Displaying longest String
System.out.println("Longest String is: " + res);
}
} Output:
Longest String is: abcdefg
Example 7: Using Stream to find the number of empty strings in an array. The filter() method is used to get a stream consisting of the elements that satisfy the given predicate. The count() method is used to count the elements of the stream.
// Java code to find the number of empty // strings in array using Stream in Java import java.util.*;
class GfG { public static void main (String[] args) { String arr[] = {"", "abc", "", "bcd", "", "", "defg", "jk"};
scss// Count the empty strings
long res = Arrays.stream(arr)
.filter(x -> x.isEmpty())
.count();
// Displaying the number of empty strings
System.out.println("Number of empty strings are: " + res);
}
} Output:
Number of empty strings are: 3
Example 8: Using Stream to find the duplicate elements in an array. The collect() method is used to accumulate the elements of the stream into a collection.
// Java code to find the duplicate elements // in array using Stream in Java import java.util.*;
class GfG { public static void main (String[] args) { String arr[] = {"abc", "bcd", "abc", "defg", "jk", "jk"};
csharp // Find duplicate elements
Set<String> set = Arrays.stream(arr)
.filter(x -> Collections.frequency(Arrays.asList(arr), x) > 1)
.collect(Collectors.toSet());
// Displaying duplicate elements
System.out.println("Duplicate elements are: " + set);
}
} Output:
Duplicate elements are: [abc, jk]
Example 9: Using Stream to find the prime numbers in an array. The isPrime() method checks if a number is prime or not.
// Java code to find the prime numbers // in array using Stream in Java import java.util.; import java.util.stream.;
class GfG { public static boolean isPrime(int n) { if (n <= 1) return false;
cppfor (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public static void main (String[] args) {
int arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
// Find the prime numbers
List<Integer> res = Arrays.stream(arr)
.filter(x -> isPrime(x))
.boxed()
.collect(Collectors.toList());
// Displaying prime numbers
System.out.println("Prime numbers are: " + set);
Thank you sir for this article
ReplyDeleteHi Babulal,
ReplyDeleteThank you for sharing your tricks and tips on your blog! I found your post on [insert relevant post] particularly helpful. I'd love to connect with you and potentially collaborate in the future. Please feel free to reach out to me through visiting my blog https://raulstrick.blogspot.com/ (RAUL'S TRICK). Looking forward to hearing back from you!