java实战一------java8的简单应用(抛砖)
你的代码很容易因为需求而变化,对自己代码改来改去的你一定会觉得烦的。在我看来,java8很容易的解决了这个问题。
先来看看例子!在一堆苹果里,筛选绿色的苹果。当然,Apple类是这样子。
1 class Apple{ 2 private Integer weight; 3 private String color; 4 public Apple(Integer weight,String color){ 5 this.weight=weight; 6 this.color=color; 7 } 8 public Integer getWeight(){ 9 return this.weight; 10 } 11 public void setWeight(Integer weight) { this.weight = weight; } 12 public String getColor() { return color; } 13 public void setColor(String color) { this.color = color; } 14 @Override 15 public String toString() { 16 return "Apple{" + 17 "weight=" + weight + 18 ", color='" + color + '\'' + 19 '}'; 20 } 21 }
View Code
一、筛选绿苹果:
public static List<Apple> findGreen(List<Apple> apples){ List<Apple> greens=new ArrayList<> (); for(Apple a:apples){ if ("green".equals (a.getColor ())){ greens.add (a); } } return greens; }
View Code
二、这次,农民又要把苹果按给的颜色分:我们加个参数就可以了。
public static List<Apple> findGreen(List<Apple> apples,String color){ List<Apple> greens=new ArrayList<> (); for(Apple a:apples){ if (color.equals (a.getColor ())){ greens.add (a); } } return greens; } }
View Code
三、然后,农民说:能分轻重就好了,你当然还是有解决方案:
1 public static Map<String,List<Apple>> findGreen(List<Apple> apples,int weight){ 2 Map<String,List<Apple>> map=new HashMap<> (); 3 List<Apple> ws=new ArrayList<> (); 4 List<Apple> ls=new ArrayList<> (); 5 for(Apple a:apples){ 6 if(weight>a.getWeight ()){ 7 ls.add (a); 8 }else { 9 ws.add (a); 10 } 11 } 12 map.put ("轻",ls); 13 map.put ("重",ws); 14 return map; 15 }
View Code
很轻松解决了问题嘛!但你会发现你在颜色和重量上又很严重的代码重复。这是,农民又有要求了,要将颜色不同的也分重量。哇,有完没完!!!
当然,这个问题可以使用策略设计模式。我就不多叙述了,我想讲的java8,好了,我终于可以奉上我的代码了。(严格来说不是我的!)
于是,我们可以走捷径了。
四,使用java8:
1 import java.util.*; 2 import java.util.stream.Collectors; 3 4 /** 5 * 觉得好玩嘛 6 */ 7 public class Demo1 { 8 public static void main(String[] args) { 9 Apple a1 = new Apple (5, "red"); 10 Apple a2 = new Apple (3, "red"); 11 Apple a3 = new Apple (10, "green"); 12 Apple a4 = new Apple (1, "green"); 13 List<Apple> list = Arrays.asList (a1, a2, a3, a4); 14 Map<String, Map<Boolean, List<Apple>>> map = list.stream ()
.collect (Collectors.groupingBy (Apple::getColor, Collectors.groupingBy (e -> { 15 return e.getWeight () > 4; 16 }))); 17 System.out.println (map); 18 } 19 }
结果:(false为轻,true为重)
map={red={false=[Apple{weight=3, color='red'}], true=[Apple{weight=5, color='red'}]},
green={false=[Apple{weight=1, color='green'}], true=[Apple{weight=10, color='green'}]}}
怎么回事,小老弟?是不是很短。java8真的很好用呢。
我会陆续的把我学的分享给大家的。