public class Test {
public static void main(String[] args) {
List<Apple> apples = Arrays.asList(
new Apple("apple1", 100L, "green"),
new Apple("apple2", 101L, "red"),
new Apple("apple3", 102L, "yellow")
);
System.out.println(filter(apples, t -> "green".equals(t.getColor())));
testConsumer(apples, t -> System.out.println(t));
System.out.println(testFunction(Arrays.asList("lambdas", "in", "action"), (String s) -> s.length()));
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> result = new ArrayList<>();
for (T t : list) {
if (p.test(t)) {
result.add(t);
}
}
return result;
}
public static <T> void testConsumer(List<T> list, Consumer<T> p) {
for (T t : list) {
p.accept(t);
}
}
public static <T, R> List<R> testFunction(List<T> list, Function<T, R> function) {
List<R> result = new ArrayList<>();
for (T t : list) {
result.add(function.apply(t));
}
return result;
}
}
public class Apple {
private String name;
private Long weight;
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Apple(String name, Long weight, String color) {
this.name = name;
this.weight = weight;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getWeight() {
return weight;
}
public void setWeight(Long weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Apple{" +
"name='" + name + '\'' +
", weight=" + weight +
", color='" + color + '\'' +
'}';
}
}