|
| 1 | +package com.brianway.learning.java8.lambda; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.function.Consumer; |
| 7 | +import java.util.function.Function; |
| 8 | +import java.util.function.Predicate; |
| 9 | + |
| 10 | +/** |
| 11 | + * Created by brian on 17/2/27. |
| 12 | + * Java 8 中常用函数式接口 |
| 13 | + */ |
| 14 | +public class FunctionDescriptor { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + //使用 Predicate |
| 18 | + Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty(); |
| 19 | + List<String> listOfStrings = Arrays.asList("aaa", "ss", ""); |
| 20 | + List<String> nonEmpty = filter(listOfStrings, nonEmptyStringPredicate); |
| 21 | + System.out.println("nonEmpty.size() == 2 " + (nonEmpty.size() == 2)); |
| 22 | + |
| 23 | + //使用 Consumer |
| 24 | + forEach(Arrays.asList(1, 2, 3, 4, 5), System.out::println); |
| 25 | + |
| 26 | + //使用 Function |
| 27 | + List<Integer> lengthsOfWord = map( |
| 28 | + Arrays.asList("lambda", "in", "action"), |
| 29 | + String::length |
| 30 | + ); |
| 31 | + forEach(lengthsOfWord, System.out::println); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * 使用 Predicate |
| 36 | + */ |
| 37 | + public static <T> List<T> filter(List<T> list, Predicate<T> p) { |
| 38 | + List<T> results = new ArrayList<>(); |
| 39 | + //TODO |
| 40 | + for (T s : list) { |
| 41 | + if (p.test(s)) { |
| 42 | + results.add(s); |
| 43 | + } |
| 44 | + } |
| 45 | + return results; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * 使用 Consumer |
| 50 | + */ |
| 51 | + public static <T> void forEach(List<T> list, Consumer<T> c) { |
| 52 | + //TODO |
| 53 | + for (T i : list) { |
| 54 | + c.accept(i); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * 使用 Function |
| 60 | + */ |
| 61 | + public static <T, R> List<R> map(List<T> list, Function<T, R> f) { |
| 62 | + List<R> result = new ArrayList<>(); |
| 63 | + //TODO |
| 64 | + for (T s : list) { |
| 65 | + result.add(f.apply(s)); |
| 66 | + } |
| 67 | + return result; |
| 68 | + } |
| 69 | +} |
0 commit comments