Java8
Posted 咸鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8相关的知识,希望对你有一定的参考价值。
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.List; 4 import java.util.function.Predicate; 5 import java.util.stream.Collectors; 6 7 /** 8 * java8实战第一章笔记 9 * 10 * @author shangjinyu 11 * @created 2017/9/29 12 */ 13 public class Notes { 14 15 //构造一个待筛选的list 16 List<Apple> inventory = Arrays.asList(new Apple(80, "green"), 17 new Apple(155, "green"), 18 new Apple(120, "red")); 19 20 //找出list中的所有的绿色苹果 21 //写法一 22 public List<Apple> filterGreenApples(List<Apple> inventory) { 23 List<Apple> result = new ArrayList<>(); 24 for (Apple apple : inventory) { 25 if (apple.getColor().equals("green")) { 26 result.add(apple); 27 } 28 } 29 return result; 30 } 31 32 //写法二 33 /*public interface Predicate<T>{ 34 boolean test(T t); 35 } 36 一个java8中的函数FunctionInterface接口 37 */ 38 public boolean isGreenApple(Apple apple) { 39 return apple.getColor().equals("green"); 40 } 41 42 public List<Apple> filterGreenApples(List<Apple> inventory, Predicate<Apple> p) { 43 List<Apple> result = new ArrayList<>(); 44 for (Apple apple : inventory) { 45 if (p.test(apple)) { 46 result.add(apple); 47 } 48 } 49 return result; 50 } 51 52 //用法 53 List<Apple> greenApples1 = filterGreenApples(inventory, this::isGreenApple); 54 //lambdasin写法 55 List<Apple> greenApples2 = filterGreenApples(inventory, (Apple apple) -> apple.getColor().equals("green")); 56 List<Apple> greenApples3 = filterGreenApples(inventory, item -> item.getColor().equals("green")); 57 //流 58 //顺序处理 59 List<Apple> greenApples4 = inventory.stream().filter(apple -> apple.getColor().equals("green")).collect(Collectors.toList()); 60 //并行处理 61 List<Apple> greenApples5 = inventory.parallelStream().filter(apple -> apple.getColor().equals("green")).collect(Collectors.toList()); 62 63 //一个实体类 64 public class Apple { 65 private int weight = 0; 66 private String color = ""; 67 68 public Apple(int weight, String color) { 69 this.weight = weight; 70 this.color = color; 71 } 72 73 public Integer getWeight() { 74 return weight; 75 } 76 77 public void setWeight(Integer weight) { 78 this.weight = weight; 79 } 80 81 public String getColor() { 82 return color; 83 } 84 85 public void setColor(String color) { 86 this.color = color; 87 } 88 89 public String toString() { 90 return "Apple{" + 91 "color=‘" + color + ‘\‘‘ + 92 ", weight=" + weight + 93 ‘}‘; 94 } 95 } 96 }
以上是关于Java8的主要内容,如果未能解决你的问题,请参考以下文章
Java8 Stream针对List先分组再求和最大值最小值平均值等