Rachit07
Rachit07

Reputation: 42

Setting multiple values in stream list using for each reference in Java 8

Below is the code snippet, I want to set isDeleted, modifiedDate & modifiedBy in a single statement using Stream API.

How can I do it?

List<CtStaticIPDetailsList> ctStaticIPDetailsList =new ArrayList()<>;

ctStaticIPDetailsList.stream().forEach(l -> l.setIsDeleted(true));

ctStaticIPDetailsList.stream()
    .forEach(l -> l.setModifiedDate(new Date()));

ctStaticIPDetailsList.stream()
    .forEach(l -> l.setModifiedBy(boqCreationDTO.getUserId()));

Upvotes: 1

Views: 1761

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28968

Don't get obsessed with streams, trying to apply them everywhere.

The operations you're performing doesn't require a generating a Stream. You can use Iterable.forEach if you want to express it with a lambda.

List<CtStaticIPDetailsList> ctStaticIPDetailsList = new ArrayList<>();
    
ctStaticIPDetailsList.forEach(l -> {
    l.setIsDeleted(true);
    l.setModifiedDate(new Date());
    l.setModifiedBy(boqCreationDTO.getUserId());
});

Also avoid using java.util.Date, this class is obsolete. Sinse Java 8 we have new Time API represented by classes like Instant, LocalDateTime, etc. which reside in the java.time package.

Upvotes: 2

Related Questions