I have a requirement where I need to create a list of objects from another list based on 2 conditions. Either the object should be in session or should be active. [This question is vaguely related to- Create list of object from another using java8 streams
class Person
{
private String firstName;
private String lastName;
private String personId;
//Getters and Setters
}
class UserInfo
{
private String uFirstName;
private String uLastName;
private String userId;
//Constructor, Getters and Setters
}
Main class:
Boolean isActiveUser = ..... [getting from upstream systems]
HttpSession session = request.session();
List<String> sessionUserIds = session.getAttribute("users");
List<Person> personList = criteria.list(); //Get list from db.
//CURRENT COCDE
List<UserInfo> userList = new ArrayList<>();
for(Person person: personList) {
UserInfo userInfo = new UserInfo(person);
if(sessionUserIds.contains(person.getPersonId())){
userInfo.setLoginTime(""); //Get LoginTime from upstream
userInfo.setIdleTime(""); // Get IdleTime from Upstream
userList.add(userInfo);
} else {
if(isActiveUser) {
userList.add(userInfo);
}
}
}
// Trying to GET IT converted to JAVA-8
List<UserInfo> userList = personList.stream()
.filter(p -> ??)
.map( ??
.collect(Collectors.toList());
Any help would be appreciated.
filterbecause you need both paths of the conditional branch. While you could obviously write this using streams, I think it's going to actually be much less readable than what you've currently got.filter, but it probably wouldn't look that much better... do you really need to reset login time and idle time only for the users in the session user id list? Do you even need that information to belong to the user info?