1

I'm just trying out lambdas in Java 8 and I'm quite disappointed because I cannot use them for instance on a plain List. Instead I always have to convert the List to a Stream and then convert back again via .collect().

Is this the ways it's supposed to be or am I doing something wrong? Maybe the solution is to replace uses of the good old Collection with Stream where possible so .map and .filter can be used more naturally everywhere. However, I'm not sure whether this is considered good practice. Am I missing another trick to work around this problem?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
lex82
  • 11,173
  • 2
  • 44
  • 69
  • 1
    See [here](http://www.lambdafaq.org/why-are-stream-operations-not-defined-directly-on-collection/). There's a duplicate somewhere... – Sotirios Delimanolis Dec 08 '15 at 16:07
  • 2
    You can still look at `Collection#removeIf` / `List#replaceAll` (with a mapping from `T` to `T`) if you wish to modify the list in place. You might be also interested by this thread: http://stackoverflow.com/questions/24676877/should-i-return-a-collection-or-a-stream – Alexis C. Dec 08 '15 at 16:07
  • 2
    No, you got it, using `stream()` and `collect()` is the intended way. If you want a more fluent API, go for an alternative collection library, such as [Goldman-Sachs Collections](https://github.com/goldmansachs/gs-collections/), [HPPC](https://github.com/vsonnier/hppcrt) etc., or just a more potent streaming library, like [StreamEx](https://github.com/amaembo/streamex). – Petr Janeček Dec 08 '15 at 16:08
  • It's all discussed [here](http://stackoverflow.com/questions/28459498/why-are-java-streams-once-off). – Sotirios Delimanolis Dec 08 '15 at 16:12
  • Ok, thanks all. I think my question is answer with the combination of the Sotirios Delimanolis link and @Slanec's answer. – lex82 Dec 08 '15 at 16:25

1 Answers1

2

forEach is defined directly on List. But for most operations, the expected use is something like:

convertedList = myList.stream().filter(...).map(...).collect(Collectors.toList());

so the conversion to and from a stream is pretty fluid.

khelwood
  • 55,782
  • 14
  • 81
  • 108