Last Updated : 11 Jul, 2025
Given a Parallel Stream in Java, the task is to reverse its elements.
Examples:Input: Parallel Stream = {11, 22, 33, 44} Output: {44, 33, 22, 11} Input: Parallel Stream = {a, b, c, d} Output: {d, c, b, a}
Below are the various ways to do so:
// Java program to reverse elements
// of a parallel Stream
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to reverse
// the elements of the parallel stream
public static <T> Collector<T, ?, Stream<T> > reverseStream()
{
return Collectors
.collectingAndThen(Collectors.toList(),
list -> {
Collections.reverse(list);
return list.stream();
});
}
// Driver code
public static void main(String[] args)
{
// Get the parallel stream
List<Integer> lists = Arrays.asList(11, 22, 33, 44);
Stream<Integer> stream = lists.parallelStream();
// Reverse and print the elements
stream.collect(reverseStream())
.forEach(System.out::println);
}
}
// Java program to reverse elements
// of a parallel Stream
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to reverse
// the elements of the parallel stream
public static <T> Iterator<T> reverseStream(Stream<T> stream)
{
return stream
.collect(Collectors
.toCollection(LinkedList::new))
.descendingIterator();
}
// Driver code
public static void main(String[] args)
{
// Get the parallel stream
List<Integer> lists = Arrays.asList(11, 22, 33, 44);
Stream<Integer> stream = lists.parallelStream();
// Reverse and print the elements
Iterator<Integer> reverse = reverseStream(stream);
reverse.forEachRemaining(System.out::println);
}
}
// Java program to reverse elements
// of a parallel Stream
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to reverse
// the elements of the parallel stream
public static <T> Stream<T> reverseStream(Stream<T> stream)
{
return stream
.collect(
Collector.of(
() -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> {
b.addAll(a);
return b;
}))
.stream();
}
// Driver code
public static void main(String[] args)
{
// Get the parallel stream
List<Integer> lists = Arrays.asList(11, 22, 33, 44);
Stream<Integer> stream = lists.parallelStream();
// Reverse and print the elements
reverseStream(stream)
.forEach(System.out::println);
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4