New gameplay of JDK8 (Lambda expression)

How long have you not gone to bed before ten o'clock?

Functional thinking

Object-oriented thinking: emphasize doing things through objects.
Functional thinking: try to ignore the complex object-oriented syntax: "emphasize what to do, not how to do it", Lambda expressions are the embodiment of functional thinking

Lambda expression

standard format

Format: (formal parameters) -> (code block)
Essence: an anonymous function (anonymous method); omit the name of the method (born in JDK8), the main function in Java is to simplify the writing of anonymous inner classes

Prerequisites for use

There is an interface, and there is only one abstract method in the interface

Omit mode

1. Parameter types can be omitted, multiple parameters are either omitted at the same time or not at all

2. If there is one and only one parameter, the parentheses that wrap the parameter can be omitted

3. If there is only one parameter code block statement, you can omit the braces and semicolons. If there is return, return also should be omitted

Precautions

1. What Java can derive is what can be omitted

2. There must be an interface, and there is only one abstract method

3. There must be a context to derive the interface corresponding to Lambda

Difference contrast

Insert picture description here

for example

	public class Test01 {
    public static void main(String[] args) {

        //1: Thread实现的匿名内部类
        new Thread(){
            @Override
            public void run() {
                System.out.println("线程启动");
            }
        }.start();
        
        //2: Runnable实习匿名内部类
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                System.out.println("线程启动");
            }
        };
        new Thread(runnable).start();
        
        //lambda创建线程
        new Thread(() -> System.out.println("线程启动")).start();
        new Thread(() -> println("线程启动")).start();   
	    }
	}

Stream related operations

characteristic
不是数据结构,没有内部存储。
不支持索引访问。
延迟计算
支持并行
很容易生成数据或集合
支持过滤,查找,转换,汇总,聚合等操作。
mechanism
1.Stream分为创建操作,中间操作,终止操作。
2.流的源可以是一个数组,集合,生成器方法,I/O通道等等
3.一个流可以有零个或多个中间操作,每一个中间操作都会返回一个新的流,供下一个操作使用,一个流只会有一个终止操作。
4.Stream只有遇到终止操作,它的源才会开始执行遍历操作。
Create operation
数组:Stream.of()
集合:stream()
通过Stream.generate方法来创建
通过Stram.iterate方法
其他
Intermediate operation
1.distinct to duplicate
List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
2.filter filter
list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());
3.sorted sort
list.stream().sorted().collect(Collectors.toList());//默认自然排序从小到大
list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());//倒序
list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
limit && skip
list.stream().limit(1).collect(Collectors.toList());
list.stream().skip(1).collect(Collectors.toList());
map induction
list.stream().map(object::getName).collect(Collectors.toList());
Terminate operation
collect
list.stream().limit(2).collect(Collectors.toList());
list.stream().limit(2).collect(Collectors.toSet());
list.stream().limit(2).collect(Collectors.toMap(Object::getName, Object::getAge));
Loop forEach
Calculate min, max, count, average
Optional<Integer> min = list.stream().reduce(Integer::min);
Optional<Integer> max = list.stream().reduce(Integer::max);
anyMatch matches any one
boolean b = list.stream().anyMatch(Object::isDel);
allMatch matches all
boolean b = list.stream().allMatch(o -> o.getAge() < 30);
noneMatch does not match
boolean b = list.stream().noneMatch(o -> o.getAge() > 30);
findFirst
Optional<Object> optional = list.stream().filter(Object::isDel).findFirst();
findAny
Optional<Object> optional = list.stream().filter(Object::isDel).findAny();
reduce protocol
List<Integer> list = Arrays.asList(1, 2, 3, 6, 8);
Integer reduce = list.stream().reduce(0, (a, b) -> a + b);
Collectors
计算总和: int i = list.stream().collect(Collectors.summingInt(Object::getMath));

Comparator<Object> 比较器 = Comparator.comparingInt(Object::getAge);
流中最大值: Optional<Object> optional = list.stream().collect(Collectors.maxBy(比较器));
流中最小值: Optional<Object> optional = list.stream().collect(Collectors.minBy(比较器));
summingInt summary
int collect = list.stream().collect(Collectors.summingInt(Object::getNum));
averagingInt average
 Double average = list.stream().collect(Collectors.averagingInt(Object::getNum));
joining connection string
String names = dish.stream().map(Object::getName).collect(Collectors.joining());

String names = dish.stream().map(Object::getName).collect(Collectors.joining(","));
counting total
long sum = list.stream().collect(Collectors.counting());
grouping By
Map<Object.Type, List<Dish>> collect = list.stream().collect(Collectors.groupingBy(Object::getType));3

//自定义分组条件
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(Person->{
        if (Person.getAge() <= 18) {
            return "未成年";
        } else if (Person.getAge() <= 40) {
            return "中年";
        } else {
            return "老年";
        }
    }));
Multi-level grouping
 Map<Person.Type, Map<String, List<Person>>> collect = list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(p -> {
        if (p.getAge() <= 18) {
            return "未成年";
        } else if (p.getAge() <= 40) {
            return "中年";
        } else {
            return "老年人";
        }
    })));

If you have any questions or different opinions, please leave a message and exchange together. The blogger will reply as soon as he sees it.

Guess you like

Origin blog.csdn.net/mrhs_dhls/article/details/105973568