Java 8速查表
|
1 2 3 | (parameters) -> expression (parameters) -> statement (parameters) -> { statements } |
1 2 3 | ( int x, int y) -> x + y () -> System.out.println( "hi " + s); (String s) -> { int n = s.length(); return n; } |
1 2 | Runnable r = () -> System.out.println( "Hello!" ); r.run(); |
1 2 | Callable<Double> pi = () -> 3.14 ; Double p = pi.call(); |
1 2 3 4 5 | String[] words = { "aaa" , "b" , "cc" }; Arrays.sort(words, (s1, s2) -> s1.length() - s2.length()); // 等價(jià)于: Arrays.sort(words, (String s1, String s2) -> s1.length() - s2.length()); |
1 2 3 4 5 | // s是高效的final變量(不會更改) String s = "foo" ; // s可以在lambdas中被引用 Runnable r = () -> System.out.println(s); |
1 2 3 4 5 | // Class::staticMethod syntax Arrays.sort(items, Util::compareItems); // 等價(jià)于: Arrays.sort(items, (a, b) -> Util.compareItems(a, b)); |
1 2 3 4 5 | // instance::instanceMethod syntax items.forEach(System.out::print); // 等價(jià)于: items.forEach((x) -> System.out.print(x)); |
1 2 3 4 5 | // Class::instanceMethod syntax items.forEach(Item::publish); // 等價(jià)于: items.forEach((x) -> { x.publish(); }); |
1 2 | ConstructorReference cref = Item:: new ; Item item = cref.constructor(); |
1 2 3 4 5 6 7 | interface Descriptive { default String desc() { return "fantastic" ; } } |
1 2 3 4 5 6 | class Item implements Descriptive { } Item x = new Item(); // prints "fantastic" System.out.println(x.desc()); |
1 2 | List<String> strings = ...; long n = strings.stream().filter(x -> !x.isEmpty()).count(); |
1 2 | List<Item> items = ...; String names = items.stream().map((x) -> x.getTitle()).collect(Collectors.joining( ", " )); |
1 2 | List<City> cities = ...; List<Country> countries = cities.stream().map((c) -> c.getCountry()).distinct().collect(Collectors.toList()); |
1 2 | List<Item> items = ...; IntSummaryStatistics stats = items.stream().mapToInt((x) -> x.getRating()).summaryStatistics(); |
|