Reputation: 2727
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.
Upvotes: 2
Views: 260
Reputation: 32046
You can work with a reducing identity to sort that out possibly. One way could be to update the implementation of mergeWith
as :
default ActionsBloc mergeWith(ActionsBloc ab) {
this.actions().addAll(Optional.ofNullable(ab)
.map(ActionsBloc::actions)
.orElse(Collections.emptyList()));
return this;
}
and then modify the grouping
and reduction
to:
this.blocs = new ArrayList<>(Stream.of(this.blocs, other.blocs)
.flatMap(Collection::stream)
.collect(groupingBy(ActionsBloc::getClass, reducing(null, ActionsBloc::mergeWith)))
.values());
Edit: As Holger pointed out such use cases of using groupingBy
and reducing
further could be more appropriately implemented using toMap
as :
this.blocs = new ArrayList<>(Stream.concat(this.blocs.stream(), other.blocs.stream())
.collect(Collectors.toMap(ActionsBloc::getClass, Function.identity(), ActionsBloc::mergeWith))
.values());
Upvotes: 4