Skip to content

Instantly share code, notes, and snippets.

Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(Optional::stream)
.flatMap(Collection::stream)
.collect(Collectors.toList());
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.map(Collection::stream).orElseGet(Stream::empty))
.collect(Collectors.toList());
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.map(Collection::stream).orElse(Stream.empty()))
.collect(Collectors.toList());
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.isPresent() ? mayHaveCars.get().stream() : Stream.empty())
.collect(Collectors.toList());
Collection<Car> markCars = people
.stream()
.filter(person -> "Mark".equals(person.getName()))
.findFirst()
.map(Person::getCars)
.filter(Optional::isPresent)
.map(Optional::get)
.orElse(Collections.emptyList());
Person mark = new Person("Mark");
List<Person> people = ...
public class Person {
private String name;
.
.
.
public Optional<Collection<Car>> getCars() {
return Optional.ofNullable(cars);
data class Employee(val name: String, val department: String)
val mark = Employee("Mark", "Accounting")
val john = Employee("John", "Management")
val smith = Employee("Smith", "Administrative")
val paul = Employee("Paul", "Accounting")
val employees = listOf(mark, john, smith, paul)
val employeesByDepartment = employees.groupBy { it.department }
public class Employee {
private final String name;
private final String department;
public Employee(final String name, final String department) {
this.name = name;
this.department = department;
}
package com.beust.coding.challenge.slidingwindowmap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author rnaufal
*