Defualt关键字
此关键字在8之前常伴随swich出现,但8把它应用到了接口上,可用它在接口中实现简单的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| interface Testy{ public void hello(); default void hi(){ System.out.println("hello"); } } class TestImp implements Testy{ @Override public void hello() { System.out.println("world"); } } public class Tes{ public static void main(String[] args) { TestImp testImp = new TestImp(); testImp.hi(); } }
|
lambda表达式
Lambda 允许把函数作为一个方法的参数(函数作为参数传递到方法中)。
核心就在于Java的lambda规范,一个接口只有一个“抽象函数”,当然可以有多个default方法,然后利用抽象函数构建lambda表达式。
举个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class LambdaD { public static void main(String[] args) { LambdaD lambdaD = new LambdaD(); LambdaT lambdaT = (a,b) -> { System.out.println(a+b); return a+b; }; lambdaD.oprate(3,5,lambdaT);
} private int oprate(int a,int b,LambdaT lambdaT){ return lambdaT.mathAdd(a,b); } } interface LambdaT{ public int mathAdd(int a,int b); }
|
变量作用域
lambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。
由此说明lambda只能引用final变量参与运算,而不能修改lambda表达式外的局部变量
举个例子:
1 2 3 4 5 6 7 8
| public static void main(String[] args) { int a1 =6; LambdaD lambdaD = new LambdaD(); LambdaT lambdaT = (a,b) -> { ++a1; System.out.println(a1); return a+b; };
|
当然,全局变量是可以让你肆意妄为的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class LambdaD { static int a1 = 5; public static void main(String[] args) { LambdaD lambdaD = new LambdaD(); LambdaT lambdaT = (a,b) -> { ++a1; System.out.println(a+b); return a+b; }; lambdaD.oprate(a1,5,lambdaT); System.out.println(a1); } private int oprate(int a,int b,LambdaT lambdaT){ return lambdaT.mathAdd(a,b); } } interface LambdaT{ public int mathAdd(int a,int b); }
|
综上:使用lambda的时候记住,你用的那个接口一定要是“函数式接口”,然后你在其中运算的时候,引入的局部变量一定是final的,是不允许被修改的,即便你没有给它final关键字,当它进入lambda的时候,他已经是final了!
Stream流
Stream是java8的新api,可以以声明的方式处理数据,是一个来自数据源的元素队列并支持聚合操作;
Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
特点:
- 不是数据结构,不会保存数据。
- 不会修改原来的数据源,它会将操作后的数据保存到另外一个对象中。
- 惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。
那么怎么生成流去操作集合呢?
在 Java 8 中, 集合接口有两个方法来生成流:
- stream() − 为集合创建串行流。
- parallelStream() − 为集合创建并行流。
串行流和并行流
串行流:故名思义,就是流操作顺序执行;
并行流:顾名思义,就是流操作并行执行;
下图很好的诠释了Stream的并行操作

代码示例一下:
1 2 3 4 5 6 7 8 9 10 11 12
| List<Integer> list1 = new List(); list1 add();... int result=0;
for( int i : myList){ result += i; }
list1.stream().sum();
mylist.stream().parallelStream().sum();
|
并行流适用场景
源集合必须可以有效拆分
拆分集合、管理 Fork/Join 任务、对象创建及 GC 也是算法上的开销,当且仅当在CPU核心上可简单完成有效拆分或者集合足够大时,才值得这样做。
因子”元素数量” * “ 每个元素的运行成本” 应该很大
CPU核心数量 - 越多越好 > 必须有1个
注意:
这部分需要对stream源码有较深的理解,通常情况我希望你能选择单一一些,遇到拆分简单的,也就是列表类型的大集合用并行,其它的用串行!
Stream的数据源
流的来源可以是集合,数组,i/o,产生器generator;
举些例子:
1 使用Collection下的 stream() 和 parallelStream() 方法
1 2 3
| List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); Stream<String> parallelStream = list.parallelStream();
|
2 使用Arrays 中的 stream() 方法,将数组转成流
1 2
| Integer[] nums = new Integer[10]; Stream<Integer> stream = Arrays.stream(nums);
|
3 使用Stream中的静态方法:of()、iterate()、generate()
1 2 3 4 5 6 7
| Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6); stream2.forEach(System.out::println); Stream<Double> stream3 = Stream.generate(Math::random).limit(2); stream3.forEach(System.out::println);
|
4 使用 BufferedReader.lines() 方法,将每行内容转成流
1 2 3
| BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt")); Stream<String> lineStream = reader.lines(); lineStream.forEach(System.out::println);
|
5 使用 Pattern.splitAsStream() 方法,将字符串分隔成流
1 2 3
| Pattern pattern = Pattern.compile(","); Stream<String> stringStream = pattern.splitAsStream("a,b,c,d"); stringStream.forEach(System.out::println);
|
Stream的中间操作
1 筛选与切片
filter:过滤流中的某些元素
limit(n):获取n个元素
skip(n):跳过n元素,配合limit(n)可实现分页
distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素
1 2 3 4 5 6 7
| Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14); Stream<Integer> newStream = stream.filter(s -> s > 5) .distinct() .skip(2) .limit(2); newStream.forEach(System.out::println);
|
2 映射
map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
1 2 3 4 5 6 7 8 9 10 11 12 13
| List<String> list = Arrays.asList("a,b,c", "1,2,3");
Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", "")); s1.forEach(System.out::println); Stream<String> s3 = list.stream().flatMap(s -> {
String[] split = s.split(","); Stream<String> s2 = Arrays.stream(split); return s2; }); s3.forEach(System.out::println);
|
3 排序
sorted():自然排序,流中元素需实现Comparable接口
sorted(Comparator com):定制排序,自定义Comparator排序器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| List<String> list = Arrays.asList("aa", "ff", "dd");
list.stream().sorted().forEach(System.out::println); Student s1 = new Student("aa", 10); Student s2 = new Student("bb", 20); Student s3 = new Student("aa", 30); Student s4 = new Student("dd", 40); List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
studentList.stream().sorted( (o1, o2) -> { if (o1.getName().equals(o2.getName())) { return o1.getAge() - o2.getAge(); } else { return o1.getName().compareTo(o2.getName()); } } ).forEach(System.out::println);
|
4 消费
peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。
1 2 3 4 5 6 7 8 9 10 11
| Student s1 = new Student("aa", 10); Student s2 = new Student("bb", 20); List<Student> studentList = Arrays.asList(s1, s2); studentList.stream() .peek(o -> o.setAge(100)) .forEach(System.out::println);
Student{name='aa', age=100} Student{name='bb', age=100}
|
Stream的终止操作
1 匹配、聚合操作
allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
findFirst:返回流中第一个元素
findAny:返回流中的任意元素
count:返回流中元素的总个数
max:返回流中元素最大值
min:返回流中元素最小值
1 2 3 4 5 6 7 8 9 10 11 12
| List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); boolean allMatch = list.stream().allMatch(e -> e > 10); boolean noneMatch = list.stream().noneMatch(e -> e > 10); boolean anyMatch = list.stream().anyMatch(e -> e > 4); Integer findFirst = list.stream().findFirst().get(); Integer findAny = list.stream().findAny().get(); long count = list.stream().count(); Integer max = list.stream().max(Integer::compareTo).get(); Integer min = list.stream().min(Integer::compareTo).get();
|
2 规约操作
Optional reduce(BinaryOperator accumulator):第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
T reduce(T identity, BinaryOperator accumulator):流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator combiner):在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24); Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get(); System.out.println(v); Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2); System.out.println(v1); Integer v2 = list.stream().reduce(0, (x1, x2) -> { System.out.println("stream accumulator: x1:" + x1 + " x2:" + x2); return x1 - x2; }, (x1, x2) -> { System.out.println("stream combiner: x1:" + x1 + " x2:" + x2); return x1 * x2; }); System.out.println(v2); Integer v3 = list.parallelStream().reduce(0, (x1, x2) -> { System.out.println("parallelStream accumulator: x1:" + x1 + " x2:" + x2); return x1 - x2; }, (x1, x2) -> { System.out.println("parallelStream combiner: x1:" + x1 + " x2:" + x2); return x1 * x2; }); System.out.println(v3);
|
3 收集操作
collect:接收一个Collector实例,将流中元素收集成另外一个数据结构。
Collector<T, A, R> 是一个接口,有以下5个抽象方法:
Supplier supplier():创建一个结果容器A
BiConsumer<A, T> accumulator():消费型接口,第一个参数为容器A,第二个参数为流中元素T。
BinaryOperator combiner():函数接口,该参数的作用跟上一个方法(reduce)中的combiner参数一样,将并行流中各 个子进程的运行结果(accumulator函数操作后的容器A)进行合并。
Function<A, R> finisher():函数式接口,参数为:容器A,返回类型为:collect方法最终想要的结果R。
Set characteristics():返回一个不可变的Set集合,用来表明该Collector的特征。有以下三个特征:
CONCURRENT:表示此收集器支持并发。(官方文档还有其他描述,暂时没去探索,故不作过多翻译)
UNORDERED:表示该收集操作不会保留流中元素原有的顺序。
IDENTITY_FINISH:表示finisher参数只是标识而已,可忽略。
Collector 工具库:Collectors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| Student s1 = new Student("aa", 10,1); Student s2 = new Student("bb", 20,2); Student s3 = new Student("cc", 10,3); List<Student> list = Arrays.asList(s1, s2, s3);
List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList());
Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet());
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")"));
Long count = list.stream().collect(Collectors.counting());
Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get();
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge));
Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge));
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge)); System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get();
|
Collectors.toList() 解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public static <T> Collector<T, ?, List<T>> toList() { return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); }
public <T> Collector<T, ?, List<T>> toList() { Supplier<List<T>> supplier = () -> new ArrayList(); BiConsumer<List<T>, T> accumulator = (list, t) -> list.add(t); BinaryOperator<List<T>> combiner = (list1, list2) -> { list1.addAll(list2); return list1; }; Function<List<T>, List<T>> finisher = (list) -> list; Set<Collector.Characteristics> characteristics = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); return new Collector<T, List<T>, List<T>>() { @Override public Supplier supplier() { return supplier; } @Override public BiConsumer accumulator() { return accumulator; } @Override public BinaryOperator combiner() { return combiner; } @Override public Function finisher() { return finisher; } @Override public Set<Characteristics> characteristics() { return characteristics; } }; }
|