-1

How can I run some logic at the end instead of collect.

for(SomeObject someObj : someObjectList){
        if (/*some test*/) {
            if (/*more tests*/) {
                // do logic like create new object with the filtered values and add to a list. 
            }
        }
    }

I can do like

someObjectList.streams().filter(test).filter(more tests).???

how can I run the logic at the end after filtering.

Thanks, Ravi

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Ravi
  • 7,939
  • 14
  • 40
  • 43

2 Answers2

3

Call .filter(...) and then .map(...) to convert elements of someObjectList, wich conform your tests into some another objects and then .collect(...). Or if you don't want to use collectors at all, add transformed objects to precreated list in .filter(...).map(...).forEach( ... ).

Marat
  • 237
  • 1
  • 10
2

One option is to use forEach, however if you are creating a list of objects you should use collect

List<Result> results = list.stream()
                           .filter(/*some test*/)
                           .filter(/*more tests*/)
                           .map(x -> new Result(x)) // do logic like create new object
                           .collect(Collectors.toList()) // add to a list. 

Functional programming involve functions which return their results and ideally don't have any side effects. However whenever you see a Runnable or Consumer you know this only exists to have side effects. IMHO this is fine provided there was no simple alternative. In this case however, instead of using forEach you really want to be creating/returning a list which is where collect(toList()) is a more natural/functional solution.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Not a down-voter, but I'd guess it's about why you honed in on `collect` when there are so many *terminal* operations: `forEach`, `forEachOrdered`, `toArray`, `reduce`, `collect`, `min`, `max`, `count`, `anyMatch`, `allMatch`, `noneMatch`, `findFirst`, `findAny`. Heck, you could even do "logic" in the non-terminate `peek`, though you shouldn't. – Andreas Apr 13 '16 at 19:17
  • 2
    @Andreas: the OP explicitly mentioned “add to a list” in the “do logic” code comment, so pointing at `collect(Collectors.toList())` is justified. And I hope, the downvote is not because of the missing semicolon… – Holger Apr 13 '16 at 20:12
  • @Andreas the OP specifically asked for new Objects to add to a list and the Stream way of doing this is with a `map` and `collect(toList())` – Peter Lawrey Apr 14 '16 at 05:47
  • @Andreas have added a note as to why `forEach` should be avoided if you want functional programming. +1 – Peter Lawrey Apr 14 '16 at 05:50