Md Sakib
Md Sakib

Reputation: 25

How to add a string field to the List of string formed by stream

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

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19555

There are several possible solutions:

  1. 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);
// ...
  1. Use 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

Related Questions