What is a Parallel stream in java?
- We have seen Sequential Stream in java, in the case of parallel stream multiple threads run simultaneously on separate cores.
- The order of execution is not maintained in the Parallel stream. It may change every time we run the program.
- A parallel stream method can create multiple threads to perform the operation.
- we can use all the methods we see in the Stream in java.
Let’s see the same example we have seen for stream by using a parallel stream in java.
import java.util.concurrent.locks.ReentrantLock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
class Test {
public static void main(String args[]) {
List<Integer> list = (List<Integer>) Arrays.asList(11, 32, 45, 12, 34, 3, 87, 14, 99, 57, 26);
// ——————- filter ——————-
List<Integer> even = list.parallelStream()
.filter(a -> a % 2 == 0)
.collect(Collectors.toList());
System.out.println(“list of even number: ” + even);
// ——————- sorted ——————-
// Natural sorting order
List<Integer> sortedList = list.parallelStream().sorted().collect(Collectors.toList());
System.out.println(“sorted list: ” + sortedList);
// Sorting in descending order using Comparator
List<Integer> sortedDescList = list.parallelStream().sorted(new Comparator<Integer>() {
public int compare(Integer v1, Integer v2) {
if(v1 < v2) {
return 1;
}
return -1;
}})
.collect(Collectors.toList());
System.out.println(“sorted list desc order: ” + sortedDescList);
// ——————- allMatch ——————-
boolean allMatch1 = list.parallelStream().allMatch(a -> a > 2);
boolean allMatch2 = list.parallelStream().allMatch(a -> a > 10);
System.out.println(“All > 2 : ” + allMatch1); // true
System.out.println(“All > 10 : ” + allMatch2); // false
// ——————- anyMatch ——————-
boolean anyMatch1 = list.parallelStream().anyMatch(a -> a > 10 && a % 3 == 0);
boolean anyMatch2 = list.parallelStream().anyMatch(a -> a > 10 && a % 10 == 0);
System.out.println(“Any value > 10 and divisible by 3 : ” + anyMatch1); // true
System.out.println(“Any value > 10 and divisible by 10 : ” + anyMatch2); // false
// ——————- noneMatch ——————-
boolean noneMatch1 = list.parallelStream().noneMatch(a -> a > 10 && a % 3 == 0);
boolean noneMatch2 = list.parallelStream().noneMatch(a -> a > 10 && a % 10 == 0);
System.out.println(“No Match > 10 and divisible by 3 : ” + noneMatch1); // false
System.out.println(“No Match > 10 and divisible by 10 : ” + noneMatch2); // true
// ——————- max ——————-
Optional<Integer> max = list.parallelStream().max(Integer::compare);
System.out.println(“Max value: ” + max.get());
// ——————- min ——————-
Optional<Integer> min = list.parallelStream().min(Integer::compare);
System.out.println(“Min value: ” + min.get());
// ——————- map ——————-
List<Integer> mapList = list.parallelStream().map(a -> a + 100).collect(Collectors.toList());
System.out.println(“mapList after adding 100 in each ” + mapList);
// ——————- group ——————-
Map<Object, List<Integer>> groupList = list.parallelStream()
.collect(Collectors.groupingBy(a -> a % 2 == 0));
System.out.println(“grouping all the even and odds ” + groupList);
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
class Test {
public static void main(String args[]) {
List<Integer> list = (List<Integer>) Arrays.asList(11, 32, 45, 12, 34, 3, 87, 14, 99, 57, 26);
// ——————- filter ——————-
List<Integer> even = list.parallelStream()
.filter(a -> a % 2 == 0)
.collect(Collectors.toList());
System.out.println(“list of even number: ” + even);
// ——————- sorted ——————-
// Natural sorting order
List<Integer> sortedList = list.parallelStream().sorted().collect(Collectors.toList());
System.out.println(“sorted list: ” + sortedList);
// Sorting in descending order using Comparator
List<Integer> sortedDescList = list.parallelStream().sorted(new Comparator<Integer>() {
public int compare(Integer v1, Integer v2) {
if(v1 < v2) {
return 1;
}
return -1;
}})
.collect(Collectors.toList());
System.out.println(“sorted list desc order: ” + sortedDescList);
// ——————- allMatch ——————-
boolean allMatch1 = list.parallelStream().allMatch(a -> a > 2);
boolean allMatch2 = list.parallelStream().allMatch(a -> a > 10);
System.out.println(“All > 2 : ” + allMatch1); // true
System.out.println(“All > 10 : ” + allMatch2); // false
// ——————- anyMatch ——————-
boolean anyMatch1 = list.parallelStream().anyMatch(a -> a > 10 && a % 3 == 0);
boolean anyMatch2 = list.parallelStream().anyMatch(a -> a > 10 && a % 10 == 0);
System.out.println(“Any value > 10 and divisible by 3 : ” + anyMatch1); // true
System.out.println(“Any value > 10 and divisible by 10 : ” + anyMatch2); // false
// ——————- noneMatch ——————-
boolean noneMatch1 = list.parallelStream().noneMatch(a -> a > 10 && a % 3 == 0);
boolean noneMatch2 = list.parallelStream().noneMatch(a -> a > 10 && a % 10 == 0);
System.out.println(“No Match > 10 and divisible by 3 : ” + noneMatch1); // false
System.out.println(“No Match > 10 and divisible by 10 : ” + noneMatch2); // true
// ——————- max ——————-
Optional<Integer> max = list.parallelStream().max(Integer::compare);
System.out.println(“Max value: ” + max.get());
// ——————- min ——————-
Optional<Integer> min = list.parallelStream().min(Integer::compare);
System.out.println(“Min value: ” + min.get());
// ——————- map ——————-
List<Integer> mapList = list.parallelStream().map(a -> a + 100).collect(Collectors.toList());
System.out.println(“mapList after adding 100 in each ” + mapList);
// ——————- group ——————-
Map<Object, List<Integer>> groupList = list.parallelStream()
.collect(Collectors.groupingBy(a -> a % 2 == 0));
System.out.println(“grouping all the even and odds ” + groupList);
}
}
Output:
list of even number: [32, 12, 34, 14, 26]sorted list: [3, 11, 12, 14, 26, 32, 34, 45, 57, 87, 99]
sorted list desc order: [99, 87, 57, 45, 34, 32, 26, 14, 12, 11, 3]
All > 2 : true
All > 10 : false
Any value > 10 and divisible by 3 : true
Any value > 10 and divisible by 10 : false
No Match > 10 and divisible by 3 : false
No Match > 10 and divisible by 10 : true
Max value: 99
Min value: 3
mapList after adding 100 in each [111, 132, 145, 112, 134, 103, 187, 114, 199, 157, 126]
grouping all the even and odds {false=[11, 45, 3, 87, 99, 57], true=[32, 12, 34, 14, 26]}
What is the difference between Sequential Stream and Parallel Stream?
Sequential Stream | Parallel Stream |
Order is maintained in the sequential stream. | Because of the simultaneous run, the order of the operation is not maintained. |
This uses a single core of the computer to run. | This uses multiple cores of the computer. |
Performance is poor since takes time to run. | Performance is high. |
More reliable since sequential run causes less error. | Less reliable since simultaneous runs can cause errors in the program/calculation. |
This is platform-independent. | This is platform-dependent. |
Let’s see the programmatical difference between Sequential Stream and Parallel Stream:
- From the example we can see that order of the sequence of an array is changed when elements are printed using a parallel stream.
import java.util.Arrays;
import java.util.List;
class Test {
public static void main(String args[]) {
List<Integer> list = (List<Integer>) Arrays.asList(11, 32, 45, 12, 34, 3, 87, 14, 99, 57, 26);
// Sequential Stream
System.out.println(“Output for Sequential Stream: “);
list.stream().forEach(a -> System.out.print(” ” + a));
System.out.println();
// Parallel Stream
System.out.println(“Output for Parallel Stream: “);
list.parallelStream().forEach(a -> System.out.print(” ” + a));
}
}
import java.util.List;
class Test {
public static void main(String args[]) {
List<Integer> list = (List<Integer>) Arrays.asList(11, 32, 45, 12, 34, 3, 87, 14, 99, 57, 26);
// Sequential Stream
System.out.println(“Output for Sequential Stream: “);
list.stream().forEach(a -> System.out.print(” ” + a));
System.out.println();
// Parallel Stream
System.out.println(“Output for Parallel Stream: “);
list.parallelStream().forEach(a -> System.out.print(” ” + a));
}
}
Output:
Output for Sequential Stream: 11 32 45 12 34 3 87 14 99 57 26
Output for Parallel Stream:
87 14 3 57 26 99 11 12 45 32 34
- Following example is to add all numbers in an array and add 10 into the total. From the array we can see that 4+6+8+2 is 20 and adding 10 into the total will be 30. So the final sum should be 30. If we are using a stream and parallel stream to add the numbers, Sequential stream will give the correct output while the parallel stream will give the incorrect output. This means simultaneous runs can cause errors in the program/calculation for Parallel Stream.
import java.util.Arrays;
import java.util.List;
class Test {
public static void main(String args[]) {
int add = 10;
List<Integer> list = (List<Integer>) Arrays.asList(4, 6, 8, 2);
int sum1 = list.stream().reduce(add, Integer::sum);
System.out.println(“Sum by using stream: ” + sum1);
int sum2 = list.parallelStream().reduce(add, Integer::sum);
System.out.println(“Sum by using parallelStream: ” + sum2);
}
}
import java.util.List;
class Test {
public static void main(String args[]) {
int add = 10;
List<Integer> list = (List<Integer>) Arrays.asList(4, 6, 8, 2);
int sum1 = list.stream().reduce(add, Integer::sum);
System.out.println(“Sum by using stream: ” + sum1);
int sum2 = list.parallelStream().reduce(add, Integer::sum);
System.out.println(“Sum by using parallelStream: ” + sum2);
}
}
Output:
Sum by using stream: 30Sum by using parallelStream: 60