0

I have a method look like this.

public void some(..., Collection<? super Some> collection) {
    // WOOT, PECS!!!
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
}

And how can I make this method returns given collection instance type-safely?

I tried this.

public <T extends Collection<? super Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection)); // error.
    return collection; // this is what I want to do
}
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • 1
    `.collect(toCollection(() -> collection))` violates the contract, as the supplier is supposed to return an empty new collection on each evaluation. There are a lot of scenarios where this can break. Just use `.forEachOrdered(collection::add)` instead. This should also fix your compile problem. – Holger Jul 13 '18 at 11:28

1 Answers1

0

I found I have to do this

public <T extends Collection<Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
    return collection; // this is what I want to do
}

So that I can do this

List<Some> list = some(..., new ArrayList<>();

I wish I can explain.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • 2
    And what is the goal of pâssing the collection as parameter ? Like choose when call the method the type of collection you have List, Set, .. ? – azro Jul 13 '18 at 06:40
  • 1
    If that’s your intended use case, just use `public > T some(..., Supplier s) { return getStream().collect(toCollection(s)); }`. Then, you can write `List list = some(..., ArrayList::new);` – Holger Jul 13 '18 at 11:31