Skip to content

Instantly share code, notes, and snippets.

@shui
Last active November 2, 2017 01:20
Show Gist options
  • Save shui/4fc515c0d2686fc24a591c10a8175ed2 to your computer and use it in GitHub Desktop.
Save shui/4fc515c0d2686fc24a591c10a8175ed2 to your computer and use it in GitHub Desktop.
public class FilteringApples {
public static List<Apple> filterGreenApple(List<Apple> inventory) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if ("green".equals(apple.getColor())) {
result.add(apple);
}
}
return result;
}
public static boolean isGreenApple(Apple apple) {
return "green".equals(apple.getColor());
}
static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
List<Apple> inventory = Arrays.asList(new Apple(80, "green"),
new Apple(155, "green"),
new Apple(120, "red"));
List<Apple> greenApples1 = filterGreenApple(inventory);
List<Apple> greenApples2 = filterApples(inventory, FilteringApples::isGreenApple);
List<Apple> greenApples3 = filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));
List<Apple> greenApples4 = inventory.stream().filter((Apple a) -> "green".equals(a.getColor()))
.collect(Collectors.toList());
List<Apple> greenApples5 = inventory.parallelStream().filter((Apple a) -> "green".equals(a.getColor()))
.collect(Collectors.toList());
}
public static class Apple {
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment