Java8 stream reduce problem

The

reduce method has three override methods:

Optional<T> reduce(BinaryOperator<T> accumulator);
T reduce(T identity, BinaryOperator<T> accumulator);
<U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner);

would you like to ask whether the return value of reduce must be the type of List generics? For example, can the return value of List < ObjectA > objects;
objects.stream.reduce ();
be of type ObjectA? Can"t you return a value added by attributes such as ObjectA? If ObjectA has a field of type int, I want to return the cumulative value of this field

Apr.09,2021

if you simply add, just mapToInt and then sum .


from the question of the subject, we can see that ObjectA is not the final returned data of stream . The final returned data is an attribute or the relevant calculation result of the attribute in ObjectA . Then this is very consistent with the third method posted by the subject. The final return type is U , not T . The three parameters of this method mean:

  1. U identity , the default value returned when the T type flow is empty
  2. BiFunction < U,? Super T, U > accumulator , how to convert a U and a T into a U
  3. BinaryOperator < U > combiner , how two U are merged into one U
The title of

becomes the subject (since this is based on object operations, it is recommended that the attribute in ObjectA be modified into a wrapper class Integer)

  1. Integer identity , return the default Integer value
  2. BiFunction < Integer,? Super ObjectA, Integer > accumulator , a Integer and a ObjectA how to convert into a Integer
  3. BinaryOperator < Integer > combiner , how two Integer are merged into one Integer

combined with my previous answer to reduce method https://codeshelper.com/q/10.

you can simply write such a code

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ObjectA {

    private Integer score;
}

Test class:

Integer reduce = Arrays.asList(o, o1, o2).stream().reduce(Integer.valueOf(0), ((integer, objectA) -> Integer.sum(integer, objectA.getScore())), Integer::sum);

if you need multiple attributes in ObjectA for accumulation or other operations, you can modify

in the second parameter.
Integer reduce = Arrays.asList(o, o1, o2).stream().reduce(Integer.valueOf(0), integer.intValue() + objectA.getScore1().intValue() + objectA.getScore2().intValue()), Integer::sum);
All in all, it is OK, but it is not recommended to change it directly. It is recommended to encapsulate the values that the business needs to return instead of changing it here. Just package objectA.getScore1 (). IntValue () + objectA.getScore2 (). IntValue () into a objectA.getXXX () method to return your calculation results. The above is for reference only.
Menu