Last active
November 2, 2017 01:20
-
-
Save shui/4fc515c0d2686fc24a591c10a8175ed2 to your computer and use it in GitHub Desktop.
Use Java 8 lambda expression...See https://github.com/java8/Java8InAction/blob/master/src/main/java/lambdasinaction/chap1/FilteringApples.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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