I have a list of array of 2 objects:
List<Object[2]>
Where object[0] is an Integer and object[1] is a String.
How can I stream the list and apply different functions on each object? So that, the result will be an array having:
result[0] = multiplication of all object[0]
result[1] = concatenation of all object[1]
We can perform a reduction operation on elements of a Java Stream using the Stream. reduce() method that returns an Optional describing the reduced object or the reduced value itself.
Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
Syntax : Stream<T> limit(long N) Where N is the number of elements the stream should be limited to and this function returns new stream as output. Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function.
With JDK-12, you can use
Object[] array = list.stream()
.collect(Collectors.teeing(
Collectors.reducing(1, a -> (Integer)a[0], (a,b) -> a * b),
Collectors.mapping(a -> (String)a[1], Collectors.joining()),
(i,s) -> new Object[] { i, s}
));
but you really should rethink your data structures.
This answer shows a version of the teeing
collector which works under Java 8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With