Java Lambda示例
jopen
10年前
Lambda表达式 —— 用简单的方法实现只有一个函数的接口
Lambda syntax
1 2 3 </td> | (parameters) -> expression (parameters) -> statement (parameters) -> { statements } | </tr> </tbody> </table> </div> </div>
1 2 3 </td> | (intx,inty) -> x + y () -> System.out.println("hi "+ s); (String s) -> {intn = s.length();returnn; } | </tr> </tbody> </table> </div> </div>
1 2 </td> | Runnable r = () -> System.out.println("Hello!"); r.run(); | </tr> </tbody> </table> </div> </div>
1 2 </td> | Callable<Double> pi = () ->3.14; Double p = pi.call(); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 </td> | String[] words = {"aaa","b","cc"}; Arrays.sort(words, (s1, s2) -> s1.length() - s2.length()); // 等价于: Arrays.sort(words, (String s1, String s2) -> s1.length() - s2.length()); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 </td> | // s是高效的final变量(不会更改) String s ="foo"; // s可以在lambdas中被引用 Runnable r = () -> System.out.println(s); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 </td> | // Class::staticMethod syntax Arrays.sort(items, Util::compareItems); // 等价于: Arrays.sort(items, (a, b) -> Util.compareItems(a, b)); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 </td> | // instance::instanceMethod syntax items.forEach(System.out::print); // 等价于: items.forEach((x) -> System.out.print(x)); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 </td> | // Class::instanceMethod syntax items.forEach(Item::publish); // 等价于: items.forEach((x) -> { x.publish(); }); | </tr> </tbody> </table> </div> </div>
1 2 </td> | ConstructorReference cref = Item::new; Item item = cref.constructor(); | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 6 7 </td> | interfaceDescriptive { defaultString desc() { return"fantastic"; } } | </tr> </tbody> </table> </div> </div>
1 2 3 4 5 6 </td> | classItemimplementsDescriptive { } Item x =newItem(); // prints "fantastic" System.out.println(x.desc()); | </tr> </tbody> </table> </div> </div>
1 2 </td> | List<String> strings = ...; longn = strings.stream().filter(x -> !x.isEmpty()).count(); | </tr> </tbody> </table> </div> </div>
1 2 </td> | List<Item> items = ...; String names = items.stream().map((x) -> x.getTitle()).collect(Collectors.joining(", ")); | </tr> </tbody> </table> </div> </div>
1 2 </td> | List<City> cities = ...; List<Country> countries = cities.stream().map((c) -> c.getCountry()).distinct().collect(Collectors.toList()); | </tr> </tbody> </table> </div> </div>
1 2 | List<Item> items = ...; IntSummaryStatistics stats = items.stream().mapToInt((x) -> x.getRating()).summaryStatistics(); |