zoukankan      html  css  js  c++  java
  • java8 流

    实现:赛选苹果

    基类

    public class Apple {
    	private String color;
    	private int weight;
    	
    	
    	public String getColor() {
    		return color;
    	}
    	public void setColor(String color) {
    		this.color = color;
    	}
    	public int getWeight() {
    		return weight;
    	}
    	public void setWeight(int weight) {
    		this.weight = weight;
    	}
    	
    	public static boolean isGreenApple(Apple apple) {
    		return "green".equals(apple.getColor());
    	}
    	public static boolean isHeavyApple(Apple apple) {
    		return apple.getWeight() > 150;
    	}
    }
    

      方法类:

        原始做法   
         public static List<Apple> filterGreenApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple: inventory){ if ("green".equals(apple.getColor())) { result.add(apple); } } return result; } public static List<Apple> filterHeavyApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple: inventory){ if (apple.getWeight() > 150) { result.add(apple); } } return result; } java8 做法 //---------------------------------------------------------------------- static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) { List<Apple> result = new ArrayList<>(); for (Apple apple: inventory){ if (p.test(apple)) { result.add(apple); } } return result; } public static void main(String[] args) { List<Apple> inventory = new ArrayList<>(); List<Apple> result = filterApples(inventory, (Apple a)-> "green".equals(a.getColor())); }

     知识点:

     

    如上图,接口类,可以写default 开头的方法,此方法可以直接写实现,而且,子类不用集成此方法

  • 相关阅读:
    Cheatsheet: 2013 12.01 ~ 12.16
    Cheatsheet: 2013 11.12 ~ 11.30
    Cheatsheet: 2013 11.01 ~ 11.11
    Cheatsheet: 2013 10.24 ~ 10.31
    Cheatsheet: 2013 10.09 ~ 10.23
    Cheatsheet: 2013 10.01 ~ 10.08
    Cheatsheet: 2013 09.22 ~ 09.30
    Cheatsheet: 2013 09.10 ~ 09.21
    Cheatsheet: 2013 09.01 ~ 09.09
    Cheatsheet: 2013 08.20 ~ 08.31
  • 原文地址:https://www.cnblogs.com/sg9527/p/7840322.html
Copyright © 2011-2022 走看看