Skip to content

Instantly share code, notes, and snippets.

private String getEmployeeStreet(Long employeeId) {
Optional<Employee> employee = Optional.of(findEmployeeById(employeeId));
return employee.map(Employee::getAddress)
.map(Address::getStreet)
.orElse(EMPTY);
}
Comparator<String> nullFirstCompare = Comparator.nullsFirst(String::compareTo);
Comparator<Employee> comparator =
Comparator.comparing(Employee::getLastName)
.thenComparing(Employee::getFirstName)
.thenComparing(Employee::getMiddleName, nullFirstCompare);
@Override
public int compareTo(Employee other) {
return comparator.compare(this, other);
package com.tom.zombie;
public class Zombie {
public enum Type {
WALKER(1),
RUNNER(1),
FATTY(2),
ABOMINATION(3);
public static Matcher<Zombie> is(Zombie.Type type) {
return new TypeSafeMatcher<Zombie>() {
@Override
protected boolean matchesSafely(Zombie zombie) {
return zombie.getType() == type;
}
@Override
public void describeTo(Description description) {
description.appendText("Zombie should be " + type);
package com.tom.zombie;
import org.junit.Test;
import static com.tom.ZombieMatcher.*;
import static com.tom.zombie.Zombie.Type.WALKER;
import static org.junit.Assert.assertThat;
public class ZombieTest {
package com.tom;
import com.tom.zombie.Zombie;
import org.hamcrest.Matcher;
public class ZombieMatcher {
public static Matcher<Zombie> is(Zombie.Type type) {
return new FuncTypeSafeMatcher<Zombie>(z -> z.getType() == type,
(d) -> d.appendText("Zombie should be " + type),
public class Zombie implements Comparable<Zombie> {
public enum Type {
WALKER, RUNNER,
FATTY, ABOMINATION;
}
Type type;
public Zombie(Type type) {
this.type = type;
public class Zombie1Test {
Zombie walker = new Zombie(WALKER);
Zombie fatty = new Zombie(FATTY);
@Test
public void shouldUseCompareMethods() {
assertTrue(walker.compareTo(fatty) < 0);
assertTrue(fatty.compareTo(walker) > 0);
assertTrue(fatty.compareTo(fatty) == 0);
public interface Compares<T> extends Comparable<T> {
default boolean isLessThan(T other) {
return compareTo(other) < 0;
}
default boolean isGreaterThan(T other) {
return compareTo(other) > 0;
}
public class Zombie implements Compares<Zombie>
... remainder of Zombie code is unchanged
public class Zombie2Test {
Zombie walker = new Zombie(WALKER);
Zombie fatty = new Zombie(FATTY);
@Test