Skip to content

Instantly share code, notes, and snippets.

@mrjink
Last active November 13, 2021 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrjink/b99a290d42a5f21ef2289bcca50e8e50 to your computer and use it in GitHub Desktop.
Save mrjink/b99a290d42a5f21ef2289bcca50e8e50 to your computer and use it in GitHub Desktop.
Medium — java-8-lambdas — Step 0
public interface Animal {
boolean canHop();
boolean canSwim();
default String getName() {
return getClass().getSimpleName();
}
}
@FunctionalInterface
public interface AnimalMatcher {
boolean matches(Animal animal);
}
public class Fish implements Animal {
@Override
public boolean canHop() {
return false;
}
@Override
public boolean canSwim() {
return true;
}
}
public class Frog implements Animal {
@Override
public boolean canHop() {
return true;
}
@Override
public boolean canSwim() {
return true;
}
}
public class Kangaroo implements Animal {
@Override
public boolean canHop() {
return true;
}
@Override
public boolean canSwim() {
return false;
}
}
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Animal> animals = Arrays.asList(new Frog(), new Kangaroo(), new Fish());
AnimalMatcher hopMatcher = new HopMatcher();
AnimalMatcher swimMatcher = new SwimMatcher();
for (Animal animal : animals) {
if (hopMatcher.matches(animal)) {
System.out.println(animal.getName() + " can hop!");
}
if (swimMatcher.matches(animal)) {
System.out.println(animal.getName() + " can swim!");
}
}
}
private static class HopMatcher implements AnimalMatcher {
@Override
public boolean matches(Animal animal) {
return animal.canHop();
}
}
private static class SwimMatcher implements AnimalMatcher {
@Override
public boolean matches(Animal animal) {
return animal.canSwim();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment