I have this code which works fine, but I find it ugly.
@EqualsAndHashCode
public abstract class Actions {
@Getter
private List<ActionsBloc> blocs;
public Actions mergeWith(@NotNull Actions other) {
this.blocs = Stream.of(this.blocs, other.blocs)
.flatMap(Collection::stream)
.collect(groupingBy(ActionsBloc::getClass, reducing(ActionsBloc::mergeWith)))
.values()
.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
return this;
}
}
ActionsBloc
is a super type which contains a list of Action
.
public interface ActionsBloc {
<T extends Action> List<T> actions();
default ActionsBloc mergeWith(ActionsBloc ab) {
this.actions().addAll(ab.actions());
return this;
}
}
What I want to do is merge blocs
of Actions
together based on the Class
type. So I'm grouping by ActionsBloc::getClass
and then merge by calling ActionsBloc::mergeWith
.
What I find ugly is calling the values().stream()
after the first stream was ended on collect
.
Is there a way to operate only on one stream and get rid of values().stream()
, or do I have to write a custom Spliterator? In other words have only one collect
in my code.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…