ThrowableException
ThrowableException

Reputation: 1426

Create 2 objects for each element of a Java stream

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.

Upvotes: 0

Views: 1448

Answers (1)

Unmitigated
Unmitigated

Reputation: 89204

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

stringList
 .stream().flatMap(str -> Stream.of(new GoddClass(), new GoddClass(str))
 .collect(Collectors.toList());

Upvotes: 6

Related Questions