I have two Lists of type:
class User {
Long userId;
String userName;
Long workflowStatusId;
}
class WorkflowStatus {
Long workflowStatusId;
String workflowStatusName;
Long userId;
}
Each user object have workflowStatusId. Similarly, each WorkflowStatus have userId associated with them.
I am saving User
s first, which is giving me List<User> users
where workflowStatusId
is set as null for each object. Now for each of these user in users, I am making new entries in WorkflowStatus
which is giving me List<WorkflowStatus> workflowStatuses
. Now I want to set these newly inserted workflowStatusId
in my previously saved User
object, so I am trying to match userId
property in both and want to set this workflowStatusId
once that match is found. I am trying to do something like:
List<User> filteredList = users
.stream()
.filter(user -> workflowStatuses
.stream()
.allMatch(user.getUserId().equals(workflowStatus.getWorkflowStatusId)))
.map(how to set workflowStatusId in user? can i do something like user->user.setWorkflowStatusId((workflowStatus.getWorkflowStatusId)))
.collect(Collectors.toList());
Trying to find some solution, if it is possible to do using Java 8 streams
. What is the better way to Compare two Lists of different object types based on some common property in java 8?
CodePudding user response:
It is not a good idea to have side effects like setting of properties in the middle of a Stream. A better solution is to just create a Map of your User instances:
Map<Long, User> usersById =
users.stream().collect(Collectors.toMap(User::getUserId, u -> u));
Now you can simply loop through your WorkflowStatus objects:
for (WorkflowStatus status : workflowStatuses) {
Long userId = status.getUserId();
Long statusId = status.getWorkflowStatusId();
usersById.get(userId).setWorkflowStatusId(statusId);
}
CodePudding user response:
<User> filteredList = users.stream().filter(user -> workflowStatuses
.stream()
.allMatch(user.getUserId().equals(workflowStatus.getWorkflowStatusId)))
.map(how to set workflowStatusId in user? can i do something like user->user.setWorkflowStatusId((workflowStatus.getWorkflowStatusId)))
.collect(Collectors.toList());
On this generate the lamba exprestion loop on java 8
workflowStatus.foreach( data ) -> { user.setworkflowStatusId(data.getWorkflowStatusId);user.setuserId(data.getuserId);}
Or simple replace below
<User> filteredList = users.stream().filter(user -> workflowStatuses
.stream()
.allMatch(user.getUserId().equals(workflowStatus.getWorkflowStatusId)))
.map(workflowStatus.foreach( data ) -> { user.setworkflowStatusId(data.getWorkflowStatusId);user.setuserId(data.getuserId)})
.collect(Collectors.toList());