4

This works as expected

Collection<String> items = combo.getItems();
items.stream().filter(item -> item.startsWith("New")).findFirst()...

But this fails to compile. Why?

Collection items = combo.getItems();
items.stream().map(Object::toString).filter(item -> item.startsWith("New")).findFirst()...
                                                         ^^^^^^^^^^
Reuben Sivan
  • 157
  • 9
  • 5
    Because `Collection` is a *raw* type. **Don't use *raw* types**, since the entire statement become *raw* when you do. – Andreas May 14 '18 at 16:22
  • `map` takes a *raw* `Function` and hence its return type is `Object` and not a `String` – Thiyagu May 14 '18 at 16:23
  • 1
    @YCF_L It only works because you didn't use the *raw* `Collection items`. – Andreas May 14 '18 at 16:28
  • 1
    @YCF_L your demo is incorrect. The second example uses `Collection items`, not `Collection items`. – Paul May 14 '18 at 16:29
  • oops I don't notice that @Andreas – Youcef LAIDANI May 14 '18 at 16:30
  • this is correct @Paul my mistake I dont notice that – Youcef LAIDANI May 14 '18 at 16:31
  • 1
    The error is `unchecked call to raw type`. See https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html, which says "However, a non-generic class or interface type is not a raw type." This works: `Collection items = ` – Paul May 14 '18 at 16:36
  • 1
    You may also use `Collection>` which means “Collection of unknown type” rather than `Collection`, which means “I don’t use Generics”… – Holger May 15 '18 at 08:15

0 Answers0