Skip to content

Instantly share code, notes, and snippets.

View AllPeopleCarsJava9.java
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(Optional::stream)
.flatMap(Collection::stream)
.collect(Collectors.toList());
View OptionalPeopleCars.java
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.map(Collection::stream).orElseGet(Stream::empty))
.collect(Collectors.toList());
View AllPeopleCars.java
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.map(Collection::stream).orElse(Stream.empty()))
.collect(Collectors.toList());
View PeopleCars.java
Collection<Car> allPeopleCars = people
.stream()
.map(Person::getCars)
.flatMap(mayHaveCars -> mayHaveCars.isPresent() ? mayHaveCars.get().stream() : Stream.empty())
.collect(Collectors.toList());
View Cars.java
Collection<Car> markCars = people
.stream()
.filter(person -> "Mark".equals(person.getName()))
.findFirst()
.map(Person::getCars)
.filter(Optional::isPresent)
.map(Optional::get)
.orElse(Collections.emptyList());
View People.java
Person mark = new Person("Mark");
List<Person> people = ...
View Person.java
public class Person {
private String name;
.
.
.
public Optional<Collection<Car>> getCars() {
return Optional.ofNullable(cars);
View Employee.kt
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 }
View Employee.java
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;
}
View SlidingWindowMap.java
package com.beust.coding.challenge.slidingwindowmap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author rnaufal
*