Lambdas表达式示例
2017-10-09 13:46
148 查看
代码如下:
import java.util.*; public class Lambdas { public static void main(String ...args){ // Simple example Runnable r = () -> System.out.println("Hello!"); r.run(); // Filtering with lambdas List<Apple> inventory = Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")); // [Apple{color='green', weight=80}, Apple{color='green', weight=155}] List<Apple> greenApples = filter(inventory, (Apple a) -> "green".equals(a.getColor())); System.out.println(greenApples); Comparator<Apple> c = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()); // [Apple{color='green', weight=80}, Apple{color='red', weight=120}, Apple{color='green', weight=155}] inventory.sort(c); System.out.println(inventory); } public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){ List<Apple> result = new ArrayList<>(); for(Apple apple : inventory){ if(p.test(apple)){ result.add(apple); } } return result; } public static class Apple { private int weight = 0; private String color = ""; public Apple(int weight, String color){ this.weight = weight; this.color = color; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String toString() { return "Apple{" + "color='" + color + '\'' + ", weight=" + weight + '}'; } } interface ApplePredicate{ public boolean test(Apple a); } }
相关文章推荐
- jdk 8 lambda表达式 及在Android Studio的使用示例
- 正则表达式中环视的一个简单示例
- JS匹配日期和时间的正则表达式示例
- Matcher Pattern 正则表达式 示例
- Oracle SQL 正则表达式示例一则
- Java正则表达式的语法与示例
- python正则表达式判断字符串是否是全部小写示例
- Cron表示式示例;Cron表达式时间字段
- Java正则表达式的语法与示例
- Python列表推导式与生成器表达式用法示例
- js 中的switch表达式使用示例
- Lambda 表达式的示例-来源(MSDN)
- java使用正则表达式查找包含的字符串示例
- [Python]正则表达式(...)分组的扩展示例
- 常用正则表达式示例
- javascript正则表达式模糊匹配IP地址功能示例
- PHP基础示例:用正则表达式修改配置信息
- javascript中解析四则运算表达式的算法和示例
- Spark SQL常用表达式示例
- Java正则表达式的语法与示例