Skip to content

Instantly share code, notes, and snippets.

@tzachz
Created August 10, 2018 19:08
Show Gist options
  • Save tzachz/dd15627eb03142c2140fbe2f20d593b2 to your computer and use it in GitHub Desktop.
Save tzachz/dd15627eb03142c2140fbe2f20d593b2 to your computer and use it in GitHub Desktop.
Functional Collection Manipulation
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Optional;
import static TasksCompletedExample.TaskStatus.Completed;
import static TasksCompletedExample.TaskStatus.Started;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toSet;
public class TasksCompletedExample {
enum TaskStatus {
Completed, Failed, Started;
}
private static class TaskEvent {
final String taskName;
final Optional<TaskStatus> status;
private TaskEvent(String taskName, Optional<TaskStatus> status) {
this.taskName = taskName;
this.status = status;
}
public String getTaskName() {
return taskName;
}
public Optional<TaskStatus> getStatus() {
return status;
}
}
final List<TaskEvent> events = ImmutableList.of(
new TaskEvent("ejectDrive", Optional.empty()),
new TaskEvent("ejectDrive", Optional.of(Started)),
new TaskEvent("ejectDrive", Optional.of(Completed)),
new TaskEvent("closeWindow", Optional.of(Started)),
new TaskEvent("fakeEvent", Optional.empty()),
new TaskEvent("fakeEvent", Optional.of(Started)),
new TaskEvent("closeWindow", Optional.of(Completed))
);
public static void main(String[] args) {
// Return true if:
// for all task names that have at least two non-empty statuses, there exists a Completed status
boolean isCompleted = events
.stream()
.collect(groupingBy(
TaskEvent::getTaskName,
mapping(TaskEvent::getStatus, toSet())))
.values()
.stream()
.filter(set -> set.stream().filter(Optional::isPresent).count() >= 2)
.allMatch(set -> set.contains(Optional.of(Completed)));
System.out.println(isCompleted);
}
}
object TasksCompletedExample {
sealed trait TaskStatus
object TaskStatus {
case object Completed extends TaskStatus
case object Failed extends TaskStatus
case object Started extends TaskStatus
}
import TaskStatus._
case class TaskEvent(taskName: String, status: Option[TaskStatus] = None)
val events: Seq[TaskEvent] = Seq(
TaskEvent("ejectDrive"),
TaskEvent("ejectDrive", Some(Started)),
TaskEvent("ejectDrive", Some(Completed)),
TaskEvent("closeWindow", Some(Started)),
TaskEvent("fakeEvent"),
TaskEvent("fakeEvent", Some(Started)),
TaskEvent("closeWindow", Some(Completed))
)
def main(args: Array[String]): Unit = {
// Return true if:
// for all task names that have at least two non-empty statuses, there exists a Completed status
val isCompleted: Boolean = events
.groupBy(_.taskName)
.values
.map(_.flatMap(_.status))
.filter(_.size >= 2)
.forall(_.contains(TaskStatus.Completed))
println(isCompleted)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment