Java Stream Reduce of array of objects
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.
You can achieve this with reduce()
:
public void testStacko() {
List<Object[]> list = new ArrayList<>();
list.add(new Object[] {1, "foo"});
list.add(new Object[] {6, "|bar"});
list.add(new Object[] {15, "|baz"});
Object[] array = list.stream()
.reduce(
(obj1, obj2) ->
new Object[] {(int) obj1[0] * (int) obj2[0],
(String) obj1[1] + (String) obj2[1]
}
)
.get();
System.out.println(array[0]); // 90
System.out.println(array[1]); // foo|bar|baz
}