Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream Reduce of array of objects

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]
like image 825
Noor Avatar asked Jun 18 '19 13:06

Noor


People also ask

How do you reduce an array of objects in Java?

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.

What does reduce () method does in stream?

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.

Can we apply stream on Array?

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.

How do you limit a stream in Java?

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.


1 Answers

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.

like image 51
Holger Avatar answered Sep 20 '22 16:09

Holger