I'm trying to redo the functionality using Stream API, but I can't figure out how I can filter user names by date in the same way, given that both dates can be null. Can anyone help me out?
public int getNumberOfUsers(Date after, Date before) {
Set<String> uniqUsers = new HashSet<>();
for (LogRecord rec : logRecords) {
if ((after == null || rec.date.getTime() >= after.getTime()) &&
(before == null || rec.date.getTime() <= before.getTime())) {
uniqUsers.add(rec.user);
}
}
return uniqUsers.size();
}
CodePudding user response:
logRecords.stream()
.filter( rec ->
(after == null || rec.date.getTime() >= after.getTime()) &&
(before == null || rec.date.getTime() <= before.getTime())
.distinct().count()
First, it filters the your records by condition, which I haven't touched. Then, it only returns distinct elements, which is equivalent to adding to Set. Lastly, it returns the resulting count.
after
and before
variables can be used as is since they are "captured" by the closure.
CodePudding user response:
uniqUsers = logRecords.stream().filter(rec -> (after != null && rec.date.getTime() >= after.getTime()) &&
(before != null && rec.date.getTime() <= before.getTime())).collect(Collectors.toSet()).size();
CodePudding user response:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class Test {
private List<LogRecord> logRecords = new ArrayList<>();
public int getNumberOfUsers(DateRange dateRange) {
return (int)logRecords.stream()
.filter(rec -> isMatch(dateRange, rec))
.map(LogRecord::getUser)
.filter(Objects::nonNull)
.distinct()
.count();
}
public static void main(String[] args) {
Test test = new Test();
Date date = new Date();
test.logRecords.add(new LogRecord("user1", date));
test.logRecords.add(new LogRecord("user2", date));
int numberOfUsers = test.getNumberOfUsers(new DateRange(date, null));
System.out.println(numberOfUsers == 2);
}
private boolean isMatch(DateRange dateRange, LogRecord rec) {
return dateRange.isMatch(rec.getDate());
}
static class DateRange {
private final Date after;
private final Date before;
public DateRange(Date before, Date after) {
this.after = after;
this.before = before;
}
public Date getAfter() {
return after;
}
public Date getBefore() {
return before;
}
boolean isMatch(Date date) {
return (getAfter() == null || date.compareTo(getAfter()) >= 0 &&
(getBefore() == null || date.compareTo(getBefore()) <= 0));
}
}
static class LogRecord {
private String user;
private Date date;
public LogRecord(String user, Date date) {
this.user = user;
this.date = date;
}
public String getUser() {
return user;
}
public Date getDate() {
return date;
}
public void setUser(String user) {
this.user = user;
}
public void setDate(Date date) {
this.date = date;
}
}
}
I hope these codes will help you.