Reputation: 8473
I am wondering if there's a better way to rewrite the groupA method with lambda as part of the chaining operations ?
public class Id {
private final int value;
public Id(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public class Ids implements Iterable<Id> {
private final List<Id> ids;
private Ids(List<Id> ids) {
this.ids = ids;
}
public static Ids of(List<Id> ids) {
return new Ids(ids);
}
public Ids groupA() {
return Ids.of(ids.stream()
.filter(id -> id.value() > 5)
.collect(Collectors.toList()));
}
@Override
public Iterator<Id> iterator() {
return ids.iterator();
}
}
Basically I want to do something like
ids.stream()
.filter(id -> id % 10 > 5)
.collect(Collectiors.toList())
.andThen(Ids::of);
And wonder if that's possible
Upvotes: 2
Views: 111
Reputation: 100209
In my StreamEx library there's a shortcut method toListAndThen
which makes this looking more fluent:
StreamEx.of(ids)
.filter(id -> id % 10 > 5)
.toListAndThen(Ids::of);
Upvotes: 2
Reputation: 198103
Sure. You can either just do the straightforward
Ids.of(ids.stream()
.filter(id -> id % 10 > 5)
.collect(Collectors.toList()))
or you could add it to the collector:
ids.stream()
.filter(id -> id % 10 > 5)
.collect(Collectors.collectingAndThen(Collectors.toList(), Ids::of))
Upvotes: 10