Reputation: 25
I have a string field userId
, I want to add it to the list of strings which is formed by stream like this user.getFollowing.stream().toList()
public List<Post> getAllPosts(String userId) {
User user = this.findUserById(userId);
System.out.printf("Finding all posts created by %s%n", userId);
if (user != null) {
List<String> userList = user.getFollowing().stream().toList();
userList.add(userId).stream().toList();
List<Post> allPostsList = postService.findPostsCreatedByMultipleUsers(userList);
System.out.printf("Returning %d posts created by %s%n", allPostsList.size(), userId);
return allPostsList;
} else {
System.out.printf("Unable to find user by id %s%n", userId);
return null;
}
}
Upvotes: 1
Views: 498
Reputation: 19555
There are several possible solutions:
stream::toList
returns an immutable list, so if it is replaced by a mutable list, userId
may be just added:List<String> userList = user.getFollowing().stream().collect(Collectors.toCollection(ArrayList::new));
userList.add(userId);
// ...
Stream::concat
to concatenate two streams, the second is created from userId
using Stream.of
:List<String> userList = Stream.concat(
user.getFollowing().stream(),
Stream.of(userId)
)
.toList();
However, the simplest solution does not require Stream API at all:
List<String> userList = new ArrayList<>(user.getFollowing());
userList.add(userId);
Upvotes: 3