0

Is there a way to create 2 different objects for each element of a stream and collect them all at last?

For example, if I have a List<String> stringList and have a class GoddClass with a default and a customConstructor, I want to create 2 objects in one stream and collect at last

stringList
  .stream()
  .map(GoddClass::new) 
  .addAnothrObject(GoddClass::customConstructor) // Not a valid line, Just to depict what is needed
  .collect(Collectors.toList());

One stream might not be the right solution to achieve what I'm trying. But the question is out for experts.

3
  • Take a look at flatMap Commented Jul 26, 2020 at 3:09
  • @AniketSahrawat Can you elaborate? I've used flatMap(), when I had a steam mapping resulting another stream, or similar cases, but how do you fit flatMap in this scenario Commented Jul 26, 2020 at 3:12
  • 3
    Create a method that returns a List<GoddClass> with both those objects accepting a string as input and use flatMap to call it like ...stream().flatMap(str -> method(str).stream()).collect.... Commented Jul 26, 2020 at 3:38

1 Answer 1

6

.flatMap with Stream.of is most suitable in this case.

stringList
 .stream().flatMap(str -> Stream.of(new GoddClass(), new GoddClass(str))
 .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

2 Comments

when you use above you get.Cannot infer type argument(s) for <R> flatMap(Function<? super T,? extends Stream<? extends R>>)
@ThrowableException Could you provide a minimal, reproducible example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.