Demion
Demion

Reputation: 57

How to use if-else logic in Java 8 stream forEach with another list

I have a situation when the list will be returned

List<String> list2 = list
.stream()
.map(str -> someCondition(str) ? doSomething(str) : doSomethingElse(str))
.collect(Collectors.toList());

doSomething(str) - This action returns List<String>

doSomethingElse(str) -This action returns only String

Can I collect them(List<String> and String) as a common List using .collect? If you have other opinions please let me know. Thanks

Upvotes: 1

Views: 1216

Answers (1)

slim
slim

Reputation: 41223

Just as if you were writing a method, you need your statement to return a consistent type. At the moment:

 str -> someCondition(str) ? doSomething(str) : doSomethingElse(str)

... returns either List<String> or String, so the nearest common superclass is Object. You probably don't want this. I would make it always return List<String>:

Function<String,String> myFunc = str -> someCondition(str) 
     ? doSomething(str) 
     : Collections.singletonList(doSomethingElse(str));

(I've stored your function in a variable so we don't have to use it inline in later examples. You can still inline it if you prefer.)

Now how you use it depends on what you want to end up with. If you want a List<List<String>>:

List<List<String>> list2 = list
    .stream()
    .map(myFunc)
    .collect(Collectors.toList());

But since you appear to want a List<String>:

List<String> list2 = list
    .stream()
    .flatMap(myFunc.andThen(List.stream))
    .collect(Collectors.toList()); 

... or if you prefer ...

List<String> list2 = list
    .stream()
    .map(myFunc)
    .flatMap(List::stream)
    .collect(Collectors.toList()); 

Upvotes: 3

Related Questions