jdk8新特性

本文详细介绍了JDK8引入的重要新特性,包括lambda表达式、方法引用、函数式接口、默认方法、Stream API、DateTime API、Optional类、Nashorn JavaScript引擎和Base64编码。这些特性显著提升了Java的函数式编程能力,改进了日期时间处理,增强了集合操作的效率,并提供了更强大的错误处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jdk8的新特性有

  • lambda表达式
  • 方法引用
  • 函数式接口
  • 默认方法
  • Stream API
  • Date Time API
  • Optional类
  • Nashorn, JavaScript 引擎
  • Base64

一、lambda表达式

  • 定义:

允许函数作为方法的参数或者说将代码视作数据,更简洁的表示函数式接口的实例

  • lambda表达式的语法:

(parameters) -> expression 或 (parameters) ->{ statements; }

当参数只有一个的时候可以省略括号,像这样x -> 2 * x

  • lambda表达式的优势:

使代码更加简洁

  • 使用lambda表达式需要注意的地方:

不允许声明同名的参数或者局部变量,使用的外部变量必须是final或者隐式final

必须是函数式接口(显示的函数式或者隐式的(FunctionInterface接口))

代码示例:

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
        
      // 类型声明
      MathOperation addition = (int a, int b) -> a + b;
        
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
        
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> { return a * b; };
        
      // 没有大括号及返回语句
      MathOperation division = (int a, int b) -> a / b;
        
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
        
      // 不用括号
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
        
      // 用括号
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
        
      greetService1.sayMessage("Runoob");
      greetService2.sayMessage("Google");
   }
    
   interface MathOperation {
      int operation(int a, int b);
   }
    
   interface GreetingService {
      void sayMessage(String message);
   }
    
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}
  •  底层原理:

使用匿名内部类时,编译会产生一个字节码文件。而lambda表达式并不会生成字节码文件,而是在运行时会生成一个类。

原有类会新增一个方法,这个方法的方法体就是lambda表达式的代码,形成一个新类会重写方法,重写方法会调用新增的方法

二、方法引用

定义:为已有名字的方法提供一个更简洁的lambda表达式。

方法引用分为4种情况,我在一个类中定义了4个方法来区分不同的方法引用:

public class Car {
    //Supplier是jdk1.8的接口,这里和lamda一起使用了
    public static Car create(final Supplier<Car> supplier) {
        return supplier.get();
    }
 
    public static void collide(final Car car) {
        System.out.println("Collided " + car.toString());
    }
 
    public void follow(final Car another) {
        System.out.println(this.toString()+" Following the " + another.toString());
    }
 
    public void repair() {
        System.out.println("Repaired " + this.toString());
    }
}

2.1、构造器引用

一种是类构造器引用

它的语法是Class::new,或者更一般的Class< T >::new,示例如下:

    	final Car car = Car.create( Car::new );//Car::new相当于() -> new Car()
    	final List< Car > cars = Arrays.asList( car );

 另外一种是数组构造器引用

Class[]::new

        Function<Integer,Car[]> function = Car[]::new;
        Car[] apply = function.apply(5);
        System.out.println(Arrays.toString(apply));

2.2、静态方法引用

它的语法是Class::static_method,示例如下:

    	cars.forEach( Car::collide );//Car::collide相当于curCar -> Car.collide(curCar)

2.3、特定类的任意对象的方法引用

cars.forEach( Car::repair );//Car::repair相当于curCar -> curCar.repair()

2.4、特定对象的方法引用

    	final Car police = Car.create( Car::new );
    	cars.forEach( police::follow );//police::follow相当于curCar -> police.follow(curCar)

提示:如果对于你来说方法引用很难理解的话,看看后面等价的lambda表达式,是不是就容易理解多了。如果lambda表达式都理解不了的话,建议你还是先去把匿名内部类和方法重写搞懂。

ps:个人感觉lambda表达式虽然看起来很简洁,但是很难理解,特别是方法引用。难以理解的东西一般都难以维护,所以不建议使用。

三、函数式接口

函数式接口就是只有一个抽象方法,但是可能多个非抽象方法的接口。

lambda表达式只能实现函数式接口的方法。

JDK1.8之前的函数接口

  • java.lang.Runnable
  • java.util.concurrent.Callable
  • java.security.PrivilegedAction
  • java.util.Comparator
  • java.io.FileFilter
  • java.nio.file.PathMatcher
  • java.lang.reflect.InvocationHandler
  • java.beans.PropertyChangeListener
  • java.awt.event.ActionListener
  • javax.swing.event.ChangeListener

JDK 1.8 新增加的函数接口:

  • java.util.function

java.util.function 它包含了很多类,用来支持 Java的 函数式编程。

接口抽象方法功能描述
Predicate<T>
boolean test(T t);
断言型;判断函数,返回判断结果true/false
Supplier<T>
T get()
供给型;无参,返回一个指定泛型的对象
Function<T, R>
R apply(T t)
方法型;输入一个参数,得到一个结果
Consumer<T>
void accept(T t)
消费型;传入一个指定泛型的参数,无返回值

 JDK1.8函数式接口Function、Consumer、Predicate、Supplier - 简书

jdk1.8提供的函数式接口总结:

Function接口的抽象方法接收一个T类型的参数,返回一个R类型 

Bi是binary(二)的缩写,名字包含Bi的接口有两个参数

名字包含BinaryOperator的接口有两个参数,并且参数类型和返回值类型相同

名字包含UnaryOperator的接口有一个参数,并且参数类型和返回值类型相同

四、默认方法

简单说,默认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。

我们只需在方法名前面加个 default 关键字即可实现默认方法。

public interface Vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
}

下面再看看静态默认方法

public interface Vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
    // 静态方法
   static void blowHorn(){
      System.out.println("按喇叭!!!");
   }
}

五、Stream

思想:使用Stream处理集合,相当于建立了一个工厂流水线, 可以对元素队列进行筛选, 排序,聚合等。

优点:Stream API高效率、简洁的代码。

创建Stream对象的方式:

方式一:

Collection接口实现了stream方法,因此Collection的实现类可以调用stream方法获取Stream对象

方式二:

Stream.of

方式三:

Stream.builder()方法获取builder对象,然后调用build方法获取Stream对象

终结方法collect方法的参数:

Collector.toCollection

Collector.toList

Collector.toSet

分组、多级分组、分区、数据拼接

并行流

获取并行流的两种方式:

stream对象的parallel方法

parallelStream方法

六、Date Time API

java8添加了新的包java.time来对日期和时间做处理。

七、Optional类

Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

使用Optional优势:这样我们就不用显式进行空值检测。

import java.util.Optional;
 
public class Java8Tester {
   public static void main(String args[]){
   
      Java8Tester java8Tester = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
        
      // Optional.ofNullable - 允许传递为 null 参数
      Optional<Integer> a = Optional.ofNullable(value1);
        
      // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
      Optional<Integer> b = Optional.of(value2);
      System.out.println(java8Tester.sum(a,b));
   }
    
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
    
      // Optional.isPresent - 判断值是否存在
        
      System.out.println("第一个参数值存在: " + a.isPresent());
      System.out.println("第二个参数值存在: " + b.isPresent());
        
      // Optional.orElse - 如果值存在,返回它,否则返回默认值
      Integer value1 = a.orElse(new Integer(0));
        
      //Optional.get - 获取值,值需要存在
      Integer value2 = b.get();
      return value1 + value2;
   }
}

八、Nashorn JavaScript

Nashorn是一个JavaScript引擎,有了这个引擎,JavaScript可以调用Java,Java也可以调用JavaScript.

九、Base64

Java 8 内置了 Base64 编码的编码器和解码器。

Base64工具类提供了一套静态方法获取下面三种BASE64编解码器:

  • 基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/。
  • URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件。
  • MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用'\r'并跟随'\n'作为分割。编码输出最后没有行分割。

Summary A developer-focused guide to writing applications using Spring Boot. You'll learn how to bypass the tedious configuration steps so that you can concentrate on your application's behavior. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology The Spring Framework simplifies enterprise Java development, but it does require lots of tedious configuration work. Spring Boot radically streamlines spinning up a Spring application. You get automatic configuration and a model with established conventions for build-time and runtime dependencies. You also get a handy command-line interface you can use to write scripts in Groovy. Developers who use Spring Boot often say that they can't imagine going back to hand configuring their applications. About the Book Spring Boot in Action is a developer-focused guide to writing applications using Spring Boot. In it, you'll learn how to bypass configuration steps so you can focus on your application's behavior. Spring expert Craig Walls uses interesting and practical examples to teach you both how to use the default settings effectively and how to override and customize Spring Boot for your unique environment. Along the way, you'll pick up insights from Craig's years of Spring development experience. What's Inside Develop Spring apps more efficiently Minimal to no configuration Runtime metrics with the Actuator Covers Spring Boot 1.3 About the Reader Written for readers familiar with the Spring Framework. About the Author Craig Walls is a software developer, author of the popular book Spring in Action, Fourth Edition, and a frequent speaker at conferences.
Spring.Boot.in.Action.2015.12.pdfFor online information and ordering of this and other manning books, please visit www.manning.com.thepublisheroffersdiscountsonthisbookwhenorderedinquantity For more information, please contact Special sales department Manning publications co 20 Baldwin Road PO BoX 761 Shelter island. ny11964 Emailorders@manning.com @2016 by manning Publications Co. All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and manning Publications was aware of a trademark claim, the designations have been printed in initial caps ll Recognizing the importance of preserving what has been written, it is Mannings policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Manning publications co Development editor: Cynthia Kane 20 Baldwin Road Technical development editor: Robert casazza PO BoX 761 Copyeditor: Andy Carroll Shelter island. ny11964 Proofreader: Corbin Collins Technical p der John Guthrie Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN9781617292545 Printed in the united states of america 12345678910-EBM-201918171615 contents reword vii pre eface 2x about this book xii acknowledgments xu Bootstarting Spring I 1. 1 Spring rebooted Taking a fresh look at spring 2. Examining spring Boot essentials 4 What Spring Boot isn't 7 1.2 Getting started with Spring boot 8 Installing the spring boot cli 8 Initializing a spring boot project with Spring Initializr 12 3 Summary 22 Developing your first Spring Boot application 23 2.1 Putting spring boot to work 24 Examining a newly initialized spring boot project 26 Dissecting Bc iect build 30 2.2 USing starter dependencies 33 Specifying facet-based dependencies 34. Overriding starter transitive dependencies 35 CONTENTS 2.8 USing automatic configuration 37 Focusing on application functionality 37. Running the application 45. What just happened? 45 2.4 Summary 48 Customizing configuration 49 8.1 Overriding Spring Boot auto-configuration 50 Securing the application 50. Creating a custom security configuration 51. Taking another peek under the covers of auto-configuration55 8.2 Externalizing configuration with properties 57 Fine-tuning auto-configuration 58. Externally configuring application beans 64. Configuring with profiles 69 8.8 Customizing application error pages 71 3.4 Summary 74 Testing with Spring Boot 76 4.1 Integration testing auto-configuration 77 4.2 Testing web applications 79 Mocking spring MvC 80- Testing web security 83 4.3 Testing a running application 86 Starting the server on a random port 87. Testing HTML pages with selenium 88 4.4 Summary 90 Getting Groovy with the spring Boot CLI 92 5.1 Developing a Spring Boot CLI application 93 Setting up the cli project 93 Eliminating code noise with Groovy 94. What just happened? 98 5.2 Grabbing dependencies 100 Overriding default dependency versions 101. Adding dependency repositories 102 5.8 Running tests with the CLI 102 5.4 Creating a deployable artifact 105 5.5 Summary 106 CONTENTS 6 Applying Grails in Spring Boot 107 1 Using gorm for data persistence 108 2 Defining views with groovy server pages 113 6.3 Mixing spring boot with grails 3 115 Creating a new grails project 116 Defining the domain 118 Writing a grails controller 119. Creating the view 120 6.4 Summary 123 Taking a peek inside with the Actuator 124 7.1 Exploring the actuator's endpoints 125 Viewing configuration details 126. Tapping runtime metrics 133 Shutting down the application 139. Fetching application information 140 7.2 Connecting to the Actuator remote shell 141 Viewing the autoconfig report 142. Listing application beans 143 Watching application metrics 144.Invoking actuator endpoints 145 7. 3 Monitoring your application with JMX 146 7.4 Customizing the Actuator 148 Changing endpoint Ds 148 Enabling and disabling endpoints 149 Adding custom metrics and gauges 149- Creating a custom trace repository 153 Plugging in custom health indicators 155 7.5 Securing Actuator endpoints 156 7.6 Summary 159 8 Deploying Spring Boot applications 160 8.1 Weighing deployment options 161 8.2 Deploying to an application server 162 Building a WaRfile 162 Creating a production profile Enabling database migration 168 8.3 Pushing to the cloud 173 Deploying to Cloud Foundry 173 Deploying to Heroku 177 8. Summary 180 appendix a spring Boot developer Tools 187 appendix b spring Boot starters 188 appendix c Configuration properties 195 appendix d spring boot dependencies 232 index 243 In the spring of 2014, the Delivery Engineering team at Netflix set out to achieve a lofty goal: enable end-to-end global continuous delivery via a software platform that facilitates both extensibility and resiliency. my team had previously built two different applications attempting to address Netflix's delivery and deployment needs, but both were beginning to show the telltale signs of monolith-ness and neither met the goals of flexibility and resiliency. What's more, the most stymieing effect of these monolithic applications was ultimately that we were unable to keep pace with our partner's inno- vation. Users had begun to move around our tools rather than with them It became apparent that if we wanted to provide real value to the company and rap- idly innovate, we needed to break up the monoliths into small, independent services that could be released at will. Embracing a microservice architecture gave us hope that we could also address the twin goals of flexibility and resiliency. but we needed to do it on a credible foundation where we could count on real concurrency, legitimate moni- toring, reliable and easy service discovery, and great runtime performance With the jVM as our bedrock, we looked for a framework that would give us rapid velocity and steadfast operationalization out of the box. We zeroed in on Spring Boot Spring Boot makes it effortless to create Spring-powered, production-ready ser- vices without a lot of code! Indeed, the fact that a simple Spring Boot Hello World application can fit into a tweet is a radical departure from what the same functionality required on the vm only a few short years ago. Out-of-the-box nonfunctional features like security, metrics, health-checks, embedded servers, and externalized configura tion made boot an easy choice for us FOREWORD Yet, when we embarked on our Spring boot journey solid documentation was hard to come by. Relying on source code isnt the most joyful manner of figuring out how to properly leverage a frameworks features It's not surprising to see the author of mannings venerable Spring in Action take on the challenge of concisely distilling the core aspects of working with Spring Boot into another cogent book. Nor is it surprising that Craig and the Manning crew have done another tremendously wonderful job! Spring Boot in Action is an easily readable book, as weve now come to expect from Craig and manning From chapter Is attention-getting introduction to Boot and the now legend ary 9Oish-character tweetable Boot application to an in-depth analysis of Boots Actuator in chapter 7, which enables a host of auto-magical operational features required for any production application, Spring Boot in Action leaves no stone unturned. Indeed, for me, chapter 7's deep dive into the Actuator answered some of the lingering questions I've had in the back of my head since picking up Boot well over a year ago. Chapter 8s thor- ough examination of deployment options opened my eyes to the simplicity of cloud Foundry for cloud deployments. One of my favorite chapters is chapter 4, where Craig explores the many powerful options for easily testing a Boot application. From the get- o, I was pleasantly surprised with some of Springs testing features, and boot takes g advantage of them nicely As I've publicly stated before, Spring Boot is just the kind of framework the Java community has been seeking for over a decade. Its easy-to-use development features and out-of-the-box operationalization make java development fun again I,m pleased to report that Spring and spring boot are the foundation of Netflix's new continuous delivery platform. What's more, other teams at Netflix are following the same path because they too see the myriad benefits of boot It's with equal parts excitement and passion that I absolutely endorse craigs book as the easy-to-digest and fun-to-read Spring boot documentation the Java community has been waiting for since Boot took the community by storm. Craigs accessible writ- ing style and sweeping analysis of boot's core features and functionality will surely leave readers with a solid grasp of Boot(along with a joyful sense of awe for it) Keep up the great work Craig Manning Publications, and all the brilliant develop ers who have made spring boot what it is today each one of you has ensured a bright future for the JV ANDREW GLOVER MANAGER, DELIVERY ENGINEERING AT NETFLIX preface At the 1964 New York World's Fair, Walt Disney introduced three groundbreaking attractions:"“it' s a small world,”“ Great Moments with mr. Lincoln," and the“ Carouse of Progress " All three of these attractions have since moved into disneyland and walt Disney world, and you can still see them today My favorite of these is the Carousel of Progress. Supposedly, it was one of Walt Disneys favorites too. It's part ride and part stage show where the seating area rotates around a center area featuring four stages. Each stage tells the story of a family at different time periods of the 20th century-the early 1900s, the 1920s the 1940s, and recent times-highlighting the technology advances in that time period The story of innovation is told from a hand-cranked washing machine, to electric lighting and radio, to automatic dishwashers and television, to computers and voice-activated appliances In every act, the father (who is also the narrator of the show)talks about the latest inventions and says "It cant get any better only to discover that in fact, it does get better in the next act as technology progresses Although Spring doesn't have quite as long a history as that displayed in the Car- ousel of Progress, I feel the same way about Spring as"Progress Dad felt about the 20th century. Each and every Spring application seems to make the lives of developers so much better. Just looking at how Spring components are declared and wired together, we can see the following progression over the history of Spring
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值