19
19
import org .jspecify .annotations .Nullable ;
20
20
21
21
import java .util .ArrayList ;
22
+ import java .util .Collections ;
22
23
import java .util .List ;
23
24
import java .util .function .BiConsumer ;
24
25
import java .util .function .Function ;
@@ -38,7 +39,7 @@ public class GroupingByGatherer<INPUT extends @Nullable Object> implements
38
39
mappingFunction = null ;
39
40
}
40
41
41
- GroupingByGatherer (Function <@ Nullable INPUT , @ Nullable Object > mappingFunction ) {
42
+ GroupingByGatherer (final Function <@ Nullable INPUT , @ Nullable Object > mappingFunction ) {
42
43
mustNotBeNull (mappingFunction , "Mapping function must not be null" );
43
44
this .mappingFunction = mappingFunction ;
44
45
}
@@ -51,34 +52,28 @@ public Supplier<State<INPUT>> initializer() {
51
52
@ Override
52
53
public Integrator <State <INPUT >, INPUT , List <INPUT >> integrator () {
53
54
return Integrator .ofGreedy ((state , element , downstream ) -> {
54
- final Object thisMatch = mappingFunction == null ? element : mappingFunction .apply (element );
55
- if (state .working == null ) {
55
+ final Object thisMappedElement = mappingFunction == null ? element : mappingFunction .apply (element );
56
+ if (!state .working .isEmpty () && !safeEquals (state .previousMappedElement , thisMappedElement )) {
57
+ downstream .push (Collections .unmodifiableList (state .working ));
56
58
state .working = new ArrayList <>();
57
- state .working .add (element );
58
- state .pastMatch = thisMatch ;
59
- } else if (!safeEquals (state .pastMatch , thisMatch )) {
60
- downstream .push (state .working );
61
- state .working = new ArrayList <>();
62
- state .working .add (element );
63
- state .pastMatch = thisMatch ;
64
- } else {
65
- state .working .add (element );
66
59
}
60
+ state .previousMappedElement = thisMappedElement ;
61
+ state .working .add (element );
67
62
return !downstream .isRejecting ();
68
63
});
69
64
}
70
65
71
66
@ Override
72
67
public BiConsumer <State <INPUT >, Downstream <? super List <INPUT >>> finisher () {
73
68
return (state , downstream ) -> {
74
- if (state .working != null ) {
75
- downstream .push (state .working );
69
+ if (! state .working . isEmpty () ) {
70
+ downstream .push (Collections . unmodifiableList ( state .working ) );
76
71
}
77
72
};
78
73
}
79
74
80
75
public static class State <INPUT > {
81
- @ Nullable Object pastMatch = null ;
82
- @ Nullable List <INPUT > working = null ;
76
+ @ Nullable Object previousMappedElement = null ;
77
+ List <INPUT > working = new ArrayList <>() ;
83
78
}
84
79
}
0 commit comments