个人总结:
lamdba表达式:
参考网上:
http://www.cnblogs.com/franson-2016/p/5593080.html
http://blog.csdn.net/ioriogami/article/details/12782141/
简单例子:
// 1. 不需要参数,返回值为 5
() -> 5
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)
补充:
@FunctionalInterface//加了这个注解接口里面只能有一个函数
public interface Runnable { void run(); }
public interface Callable<V> { V call() throws Exception; }
public interface ActionListener { void actionPerformed(ActionEvent e); }
public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }
注意最后这个Comparator接口。它里面声明了两个方法,貌似不符合函数接口的定义,但它的确是函数接口。这是因为equals方法是Object的,所有的接口都会声明Object的public方法——虽然大多是隐式的。所以,Comparator显式的声明了equals不影响它依然是个函数接口。
如果要在内部类访问外部对象的一个本地变量,那么这个变量必须声明为final才行。在Java8中,这种限制被去掉了,代之以一个新的概念,“effectively final”。它的意思是你可以声明为final,也可以不声明final但是按照final来用,也就是一次赋值永不改变
除了默认方法,Java8的接口也可以有静态方法的实现
combiner函数,有四个线程同时去执行,生成四个结果部分
l. collect: 收集器
2. Collector作为col1ect方法的参数
3. Collector是个接口, 它是个可变的汇聚操作, 将输入元素累积到个可变的结果容器中;它会在所有元素都处理完毕后,将累积的结果转换为一个最终的表示(这是一 个可选操作) ;它
支持串行与并行两种方式执行。
4. Collectors本身提供了关于collector的常见汇聚实现,collectors本身实际上是 个工厂●
5.为了确保串行与并行操作结果的等价性,Collector函数需要满足两个条件: identity (同性)与associativity (结合性)●
6. a = combiner.apply(a, supplier .get())
(List<String> listl, List<string> list2) - {list1. addAll(list2); return list1}
A al=supplier.get();
accumulator . accept(al, t1);
accumulator .accept(a1, t2);
R rl=finisher.app1y(al); /1 result without splitting
A a2=supplier.get();
accumulator .accept(a2,t1);
A a3=supplier.get();
accumulator .accept(a3,t2);
R r2=finisher . apply(combiner .apply(a2, a3)); /1 result with splitting
combiner函数,有4个线程同时去执行,那么就会生成4个部分结果。
7 函数式编程:表示做什么,而不是如何做
Function接受一个参数返回一个结果,BIFunction接收参数返回两个结果
consumer接受参数不返回值,BIConsumer接受两个参数不返回值
BinaryOperator 接受两个参数,返回一个结果
public interface Collector<T, A, R>
T 表示 集合当中每个元素类型(输入)
A 可变容器的类型(中间)
R 结果的类型(结果)
Supplier<A> supplier(); 提供新的空的可变类型的结果,返回结果容器的类型
BiConsumer<A, T> accumulator(); A 每次处理的结果类型 T待处理的结果类型
BinaryOperator<A> combiner(); 合并两个部分结果
Function<A, R> finisher(); 接受中间A返回R
参数没有从 combiner finisher返回就再也不能使用了,认为是使用过了,没法再使用了, 利用ArrayList.addAll(combiner|finisher)之后认为使用过了,就可以再次使用了
并发的不能同时被多个线程使用 ,不能在并行流中使用 ArrayList(不指定容量).add,会引起扩容问题
Collector 实现类
java.util.stream.Collectors.CollectorImpl 静态内部类,相当于一个工具类,是一个工厂,向开发者提供常见功能
package com.lamdba;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
public class GreoupTest
{
private List<Student> students;
@Before
public void before()
{
Student zhangsan = new Student("zhangsan", 80);
Student lisi = new Student("lisi", 90);
Student wangwu = new Student("wangwu", 100);
students = new ArrayList<Student>()
{{
add(zhangsan);
add(lisi);
add(wangwu);
}};
}
//java.util.stream.Collectors.CollectorImpl
@Test
public void test()
{
//分组之后, 每个组有多少个
Map<String, Long> collect = students.stream().collect(Collectors.groupingBy(Student::getName, counting()));
collect.forEach((k, v) -> System.out.println(k + "===" + v));
System.out.println("求每个组的平均值...");
Map<String, Double> collect1 = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.averagingDouble(Student::getScore)));
collect1.forEach((k, v) -> System.out.println(k + "===" + v));
Map<Boolean, List<Student>> collect2 = students.stream().collect(Collectors.partitioningBy(student -> student.getScore() > 90));
List<Student> students1 = collect2.get(true);
List<Student> students2 = collect2.get(false);
System.out.println("大于90分的 ===" + students1);
System.out.println("count:" + students.stream().collect(counting()));
System.out.println("count:" + students.stream().count());
System.out.println("------------");
students.stream().collect(minBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
students.stream().collect(maxBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
System.out.println(students.stream().collect(averagingInt(Student::getScore)));
//270
System.out.println("summingInt==============" + students.stream().collect(summingInt(Student::getScore)));
//{count=3, sum=270, min=80, average=90.000000, max=100}
IntSummaryStatistics intSummaryStatistics = students.stream().collect(summarizingInt(Student::getScore));
System.out.println("summarizingInt==============" + intSummaryStatistics);
String collect4 = students.stream().map(Student::getName).collect(joining(",", "{", "}"));
ConcurrentMap<String, List<Student>> collect3 = students.stream().collect(groupingByConcurrent(Student::getName));
}
@Test
public void testjisuan()
{
}
@Test
public void testNull()
{
Optional<Student> collect3 = students.stream().collect(minBy(Comparator.comparingInt(Student::getScore)));
//找出最小值并打印
//ifPresent 判断是否存在
collect3.ifPresent(System.out::println);
//判空
// students.add(null);
students.stream().filter(Objects::nonNull).forEach(person ->
{
System.out.println(person.getName());
});
Optional.ofNullable(students).orElseGet(() ->
{
System.out.println("personList为null!");
return new ArrayList<>();
}).stream().filter(Objects::nonNull).forEach(person ->
{
System.out.println(person.getName());
System.out.println(person.getScore());
});
Map<String, Object> map = new HashMap<>();
map.put("text", "123");
String text = Optional.ofNullable(map.get("text"))
.map(value -> value.toString().trim())
.orElse("");
System.out.println(text);
}
@Test
public void testGroup()
{
Map<Integer, Map<String, List<Student>>> collect5 = students.stream().collect(groupingBy(Student::getScore, groupingBy(Student::getName)));
Map<Boolean, Map<Boolean, List<Student>>> collect5P = students.stream().collect(partitioningBy(student -> student.getScore() > 80, partitioningBy(student -> student.getScore() > 90)));
Map<String, Student> collect6 = students.stream().collect(groupingBy(Student::getName, collectingAndThen(minBy(Comparator.comparingInt(Student::getScore)), Optional::get)));
System.out.println(collect6);
}
}