Obaid Maroof
Obaid Maroof

Reputation: 1579

Java list map function not working

myList
.stream()
.map((question) -> {                    
     question.setQuestionId(UUID.randomUUID().toString());
     return question;
});

Following java code is not getting into the map function. Can someone please point me to what am I doing fundamentally wrong here? myList is an ArrayList with some elements in it.

Upvotes: 2

Views: 2301

Answers (2)

Nikem
Nikem

Reputation: 5784

Streams in Java are lazy. It means that no transformation, such as map, will be executed until its results is requested. The usual way to request the result of the whole stream is to use some terminal operation, such as forEach or collect. Without terminal operation nothing gets executed.

Upvotes: 4

Julien Lopez
Julien Lopez

Reputation: 1844

If you look at the documentation for java.util.stream.Stream.map, you'll see that this method returns a new stream. If you need to keep your original list, use this method and store the results in a new list:

List<...> newList = myList
                     .stream()
                     .map(question -> {                    
                       question.setQuestionId(UUID.randomUUID().toString());
                       return question;
                     })
                     .collect(Collectors.toList());

If you just need to modify your original list, since List implements Iterable, you can use java.lang.Iterable.forEach:

myList.forEach(question -> question.setQuestionId(UUID.randomUUID().toString()));

Upvotes: 4

Related Questions