在
JDK1.7的新特性方面主要有下面几方面的增强:
1.jdk7语法上
1.1二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。
-
// 所有整数 int, short,long,byte都可以用二进制表示
-
// An 8-bit 'byte' value:
-
byte aByte = (byte) 0b00100001;
-
-
// A 16-bit 'short' value:
-
short aShort = (short) 0b1010000101000101;
-
-
// Some 32-bit 'int' values:
-
intanInt1 = 0b10100001010001011010000101000101;
-
intanInt2 = 0b101;
-
intanInt3 = 0B101; // The B can be upper or lower case.
-
-
// A 64-bit 'long' value. Note the "L" suffix:
-
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
-
-
// 二进制在数组等的使用
-
final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,
-
0b00010011, 0b00100110, 0b01001100, 0b10011000 };
1.2 Switch语句支持string类型
-
public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
-
String typeOfDay;
-
switch (dayOfWeekArg) {
-
case "Monday":
-
typeOfDay = "Start of work week";
-
break;
-
case "Tuesday":
-
case "Wednesday":
-
case "Thursday":
-
typeOfDay = "Midweek";
-
break;
-
case "Friday":
-
typeOfDay = "End of work week";
-
break;
-
case "Saturday":
-
case "Sunday":
-
typeOfDay = "Weekend";
-
break;
-
default:
-
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
-
}
-
return typeOfDay;
-
}
1.3 Try-with-resource语句
注意:实现java.lang.AutoCloseable接口的资源都可以放到try中,跟final里面的关闭资源类似; 按照声明逆序关闭资源 ;Try块抛出的异常通过Throwable.getSuppressed获取
点击(此处)折叠或打开
-
try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
-
java.io.BufferedWriter writer = java.nio.file.Files
-
.newBufferedWriter(outputFilePath, charset)) {
-
// Enumerate each entry
-
for (java.util.Enumeration entries = zf.entries(); entries
-
.hasMoreElements();) {
-
// Get the entry name and write it to the output file
-
String newLine = System.getProperty("line.separator");
-
String zipEntryName = ((java.util.zip.ZipEntry) entries
-
.nextElement()).getName() + newLine;
-
writer.write(zipEntryName, 0, zipEntryName.length());
-
}
-
}
1.4 Catch多个异常 说明:Catch异常类型为final; 生成Bytecode 会比多个catch小; Rethrow时保持异常类型
-
public static void main(String[] args) throws Exception {
-
try {
-
testthrows();
-
} catch (IOException | SQLException ex) {
-
throw ex;
-
}
-
}
-
public static void testthrows() throws IOException, SQLException {
-
}
1.5 数字类型的下划线表示 更友好的表示方式,不过要注意下划线添加的一些标准,可以参考下面的示例
-
long creditCardNumber = 1234_5678_9012_3456L;
-
long socialSecurityNumber = 999_99_9999L;
-
float pi = 3.14_15F;
-
long hexBytes = 0xFF_EC_DE_5E;
-
long hexWords = 0xCAFE_BABE;
-
long maxLong = 0x7fff_ffff_ffff_ffffL;
-
byte nybbles = 0b0010_0101;
-
long bytes = 0b11010010_01101001_10010100_10010010;
-
//float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point
-
//float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point
-
//long socialSecurityNumber1= 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix
-
//int x1 = _52; // This is an identifier, not a numeric literal
-
int x2 = 5_2; // OK (decimal literal)
-
//int x3 = 52_; // Invalid; cannot put underscores at the end of a literal
-
int x4 = 5_______2; // OK (decimal literal)
-
//int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix
-
//int x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number
-
int x7 = 0x5_2; // OK (hexadecimal literal)
-
//int x8 = 0x52_; // Invalid; cannot put underscores at the end of a number
-
int x9 = 0_52; // OK (octal literal)
-
int x10 = 05_2; // OK (octal literal)
-
1.6 泛型实例的创建可以通过类型推断来简化 可以去掉后面new部分的泛型类型,只用<>就可以了。
-
//使用泛型前
-
List strList = new ArrayList();
-
List<String> strList4 = new ArrayList<String>();
-
List<Map<String, List<String>>> strList5 = new ArrayList<Map<String, List<String>>>();
-
-
-
//编译器使用尖括号 (<>) 推断类型
-
List<String> strList0 = new ArrayList<String>();
-
List<Map<String, List<String>>> strList1 = new ArrayList<Map<String, List<String>>>();
-
List<String> strList2 = new ArrayList<>();
-
List<Map<String, List<String>>> strList3 = new ArrayList<>();
-
List<String> list = new ArrayList<>();
-
list.add("A");
-
// The following statement should fail since addAll expects
-
// Collection extends String>
-
1.7在可变参数方法中传递非具体化参数,改进编译警告和错误
Heap pollution 指一个变量被指向另外一个不是相同类型的变量。例如
-
List l = new ArrayList<Number>();
-
List<String> ls = l; // unchecked warning
-
l.add(0, new Integer(42)); // another unchecked warning
-
String s = ls.get(0); // ClassCastException is thrown
-
Jdk7:
-
public static <T> void addToList (List<T> listArg, T... elements) {
-
for (T x : elements) {
-
listArg.add(x);
-
}
-
}
你会得到一个warning
warning: [varargs] Possible heap pollution from parameterized vararg type
要消除警告,可以有三种方式
1.加 annotation @SafeVarargs
2.加 annotation @SuppressWarnings({"unchecked", "varargs"})
3.使用编译器参数 –Xlint:varargs;
1.8 信息更丰富的回溯追踪 就是上面try中try语句和里面的语句同时抛出异常时,异常栈的信息
java.io.IOException
§? at Suppress.write(Suppress.java:19)
§? at Suppress.main(Suppress.java:8)
§? Suppressed: java.io.IOException
§? at Suppress.close(Suppress.java:24)
§? at Suppress.main(Suppress.java:9)
§? Suppressed: java.io.IOException
§? at Suppress.close(Suppress.java:24)
§? at Suppress.main(Suppress.java:9)
2. NIO2的一些新特性
1.java.nio.file 和java.nio.file.attribute包 支持更详细属性,比如权限,所有者
2. symbolic and hard links支持
3. Path访问文件系统,Files支持各种文件操作
4.高效的访问metadata信息
5.递归查找文件树,文件扩展搜索
6.文件系统修改通知机制
7.File类操作API兼容
8.文件随机访问增强 mapping a region,locl a region,绝对位置读取
9. AIO Reactor(基于事件)和Proactor
下面列一些示例:
2.1IO and New IO 监听文件系统变化通知
通过FileSystems.getDefault().newWatchService()获取watchService,然后将需要监听的path目录注册到这个watchservice中,对于这个目录的文件修改,新增,删除等实践可以配置,然后就自动能监听到响应的事件。
-
private WatchService watcher;
-
public TestWatcherService(Path path) throws IOException {
-
watcher = FileSystems.getDefault().newWatchService();
-
path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
-
}
-
public void handleEvents() throws InterruptedException {
-
while (true) {
-
WatchKey key = watcher.take();
-
for (WatchEvent<?> event : key.pollEvents()) {
-
WatchEvent.Kind kind = event.kind();
-
if (kind == OVERFLOW) {// 事件可能lost or discarded
-
continue;
-
}
-
WatchEvent<Path> e = (WatchEvent<Path>) event;
-
Path fileName = e.context();
-
System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);
-
}
-
if (!key.reset()) {
-
break;
-
}
2.2 IO and New IO遍历文件树 ,通过继承SimpleFileVisitor类,实现事件遍历目录树的操作,然后通过Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);这个API来遍历目录树
-
private void workFilePath() {
-
Path listDir = Paths.get("/tmp"); // define the starting file
-
ListTree walk = new ListTree();
-
…Files.walkFileTree(listDir, walk);…
-
// 遍历的时候跟踪链接
-
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
-
try {
-
Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);
-
} catch (IOException e) {
-
System.err.println(e);
-
}
-
class ListTree extends SimpleFileVisitor<Path> {// NIO2 递归遍历文件目录的接口
-
@Override
-
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
-
System.out.println("Visited directory: " + dir.toString());
-
return FileVisitResult.CONTINUE;
-
}
-
@Override
-
public FileVisitResult visitFileFailed(Path file, IOException exc) {
-
System.out.println(exc);
-
return FileVisitResult.CONTINUE;
-
}
-
}
2.3 AIO异步IO 文件和网络 异步IO在java
NIO2实现了,都是用AsynchronousFileChannel,AsynchronousSocketChanne等实现,关于同步阻塞IO,同步非阻塞IO,异步阻塞IO和异步非阻塞IO在ppt的这页上下面备注有说明,有兴趣的可以深入了解下。Java NIO2中就实现了操作系统的异步非阻塞IO。
点击(此处)折叠或打开
-
// 使用AsynchronousFileChannel.open(path, withOptions(),
-
// taskExecutor))这个API对异步文件IO的处理
-
public static void asyFileChannel2() {
-
final int THREADS = 5;
-
ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
-
String encoding = System.getProperty("file.encoding");
-
List<Future<ByteBuffer>> list = new ArrayList<>();
-
int sheeps = 0;
-
Path path = Paths.get("/tmp",
-
"store.txt");
-
try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
-
.open(path, withOptions(), taskExecutor)) {
-
for (int i = 0; i < 50; i++) {
-
Callable<ByteBuffer> worker = new Callable<ByteBuffer>() {
-
@Override
-
public ByteBuffer call() throws Exception {
-
ByteBuffer buffer = ByteBuffer
-
.allocateDirect(ThreadLocalRandom.current()
-
.nextInt(100, 200));
-
asynchronousFileChannel.read(buffer, ThreadLocalRandom
-
……
3. JDBC 4.1
3.1.可以使用try-with-resources自动关闭Connection, ResultSet, 和 Statement资源对象
3.2. RowSet 1.1:引入RowSetFactory接口和RowSetProvider类,可以创建JDBC driver支持的各种 row sets,这里的rowset实现其实就是将sql语句上的一些操作转为方法的操作,封装了一些功能。
3.3. JDBC-ODBC驱动会在jdk8中删除
-
try (Statement stmt = con.createStatement()) {
-
RowSetFactory aFactory = RowSetProvider.newFactory();
-
CachedRowSet crs = aFactory.createCachedRowSet();
-
-
RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);
-
WebRowSet wrs = rsf.createWebRowSet();
-
createCachedRowSet
-
createFilteredRowSet
-
createJdbcRowSet
-
createJoinRowSet
-
createWebRowSet
4. 并发工具增强
4.1.fork-join
最大的增强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu可以同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,然后调用fork计算,最后用join合并结果。
-
class Fibonacci extends RecursiveTask<Integer> {
-
final int n;
-
Fibonacci(int n) {
-
this.n = n;
-
}
-
private int compute(int small) {
-
final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
-
return results[small];
-
}
-
public Integer compute() {
-
if (n <= 10) {
-
return compute(n);
-
}
-
Fibonacci f1 = new Fibonacci(n - 1);
-
Fibonacci f2 = new Fibonacci(n - 2);
-
System.out.println("fork new thread for " + (n - 1));
-
f1.fork();
-
System.out.println("fork new thread for " + (n - 2));
-
f2.fork();
-
return f1.join() + f2.join();
-
}
-
}
4.2.ThreadLocalRandon 并发下随机数生成类,保证并发下的随机数生成的线程安全,实际上就是使用threadlocal
-
final int MAX = 100000;
-
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
-
long start = System.nanoTime();
-
for (int i = 0; i < MAX; i++) {
-
threadLocalRandom.nextDouble();
-
}
-
long end = System.nanoTime() - start;
-
System.out.println("use time1 : " + end);
-
long start2 = System.nanoTime();
-
for (int i = 0; i < MAX; i++) {
-
Math.random();
-
}
-
long end2 = System.nanoTime() - start2;
-
System.out.println("use time2 : " + end2);
4.3. phaser 类似cyclebarrier和countdownlatch,不过可以动态添加资源减少资源
-
void runTasks(List<Runnable> tasks) {
-
final Phaser phaser = new Phaser(1); // "1" to register self
-
// create and start threads
-
for (final Runnable task : tasks) {
-
phaser.register();
-
new Thread() {
-
public void run() {
-
phaser.arriveAndAwaitAdvance(); // await all creation
-
task.run();
-
}
-
}.start();
-
}
-
// allow threads to start and deregister self
-
phaser.arriveAndDeregister();
-
}
5. Networking增强
新增URLClassLoader close方法,可以及时关闭资源,后续重新加载class文件时不会导致资源被占用或者无法释放问题
URLClassLoader.newInstance(new URL[]{}).close();
新增Sockets Direct Protocol
绕过操作系统的数据拷贝,将数据从一台机器的内存数据通过网络直接传输到另外一台机器的内存中
6. Multithreaded Custom Class Loaders
解决并发下加载class可能导致的死锁问题,这个是jdk1.6的一些新版本就解决了,jdk7也做了一些优化。有兴趣可以仔细从官方文档详细了解
jdk7前:
Class Hierarchy:
class A extends B
class C extends D
ClassLoader Delegation Hierarchy:
Custom Classloader CL1:
directly loads class A
delegates to custom ClassLoader CL2 for class B
Custom Classloader CL2:
directly loads class C
delegates to custom ClassLoader CL1 for class D
Thread 1:
Use CL1 to load class A (locks CL1)
defineClass A triggers
loadClass B (try to lock CL2)
Thread 2:
Use CL2 to load class C (locks CL2)
defineClass C triggers
loadClass D (try to lock CL1)
Synchronization in the ClassLoader class wa
jdk7
Thread 1:
Use CL1 to load class A (locks CL1+A)
defineClass A triggers
loadClass B (locks CL2+B)
Thread 2:
Use CL2 to load class C (locks CL2+C)
defineClass C triggers
loadClass D (locks CL1+D)
7. Security 增强
7.1.提供几种 ECC-based algorithms (ECDSA/ECDH) Elliptic Curve Cryptography (ECC)
7.2.禁用CertPath Algorithm Disabling
7.3. JSSE (SSL/TLS)的一些增强
8. Internationalization 增强 增加了对一些编码的支持和增加了一些显示方面的编码设置等
1. New Scripts and Characters from Unicode 6.0.0
2. Extensible Support for ISO 4217 Currency Codes
Currency类添加:
getAvailableCurrencies
getNumericCode
getDisplayName
getDisplayName(Locale)
3. Category Locale Support
getDefault(Locale.Category)FORMAT DISPLAY
4. Locale Class Supports BCP47 and UTR35
UNICODE_LOCALE_EXTENSION
PRIVATE_USE_EXTENSION
Locale.Builder
getExtensionKeys()
getExtension(char)
getUnicodeLocaleType(String
……
5. New NumericShaper Methods
NumericShaper.Range
getShaper(NumericShaper.Range)
getContextualShaper(Set
)……
9.jvm方面的一些特性增强,下面这些特性有些在jdk6中已经存在,这里做了一些优化和增强。
1.Jvm支持非java的语言 invokedynamic 指令
2. Garbage-First Collector 适合server端,多处理器下大内存,将heap分成大小相等的多个区域,mark阶段检测每个区域的存活对象,compress阶段将存活对象最小的先做回收,这样会腾出很多空闲区域,这样并发回收其他区域就能减少停止时间,提高吞吐量。
3. HotSpot性能增强
Tiered Compilation -XX:+UseTieredCompilation 多层编译,对于经常调用的代码会直接编译程本地代码,提高效率
Compressed Oops 压缩对象指针,减少空间使用
Zero-Based Compressed Ordinary Object Pointers (oops) 进一步优化零基压缩对象指针,进一步压缩空间
4. Escape Analysis 逃逸分析,对于只是在一个方法使用的一些变量,可以直接将对象分配到栈上,方法执行完自动释放内存,而不用通过栈的对象引用引用堆中的对象,那么对于对象的回收可能不是那么及时。
5. NUMA Collector Enhancements
NUMA(Non Uniform Memory Access),NUMA在多种计算机系统中都得到实现,简而言之,就是将内存分段访问,类似于硬盘的RAID,Oracle中的分簇
10. Java 2D Enhancements
1. XRender-Based Rendering Pipeline -Dsun.java2d.xrender=True
2. Support for OpenType/CFF Fonts GraphicsEnvironment.getAvailableFontFamilyNames
3. TextLayout Support for Tibetan Script
4. Support for Linux Fonts
11. Swing Enhancements
1. JLayer
2. Nimbus Look & Feel
3. Heavyweight and Lightweight Components
4. Shaped and Translucent Windows
5. Hue-Saturation-Luminance (HSL) Color Selection in JColorChooser Class
12. Jdk8 lambda表达式 最大的新增的特性,不过在很多动态语言中都已经原生支持。
原来这么写:
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
jdk8直接可以这么写:
btn.setOnAction(
event -> System.out.println("Hello World!")
);
更多示例:
public class Utils {
public static int compareByLength(String in, String out){
return in.length() - out.length();
}
}
public class MyClass {
public void doSomething() {
String[] args = new String[] {"microsoft","apple","linux","oracle"}
Arrays.sort(args, Utils::compareByLength);
}
}
13.jdk8的一些其他特性,当然jdk8的增强功能还有很多,大家可以参考
用Metaspace代替PermGen
动态扩展,可以设置最大值,限制于本地内存的大小
Parallel array sorting 新APIArrays#parallelSort.
New Date & Time API
Clock clock = Clock.systemUTC(); //return the current time based on your system clock and set to UTC.
Clock clock = Clock.systemDefaultZone(); //return time based on system clock zone
long time = clock.millis(); //time in milliseconds from January 1st, 1970
下面是JDK1.8的新特性
一、接口的默认方法
Java 8允许我们给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法,示例如下:
-
interface Formula {
-
double calculate(int a);
-
-
-
default double sqrt(int a) {
-
return Math.sqrt(a);
-
}
-
}
Formula接口在拥有calculate方法之外同时还定义了sqrt方法,实现了Formula接口的子类只需要实现一个calculate方法,默认方法sqrt将在子类上可以直接使用。
-
Formula formula = new Formula() {
-
@Override
-
public double calculate(int a) {
-
return sqrt(a * 100);
-
}
-
};
-
-
-
formula.calculate(100); // 100.0
-
formula.sqrt(16);
文中的formula被实现为一个匿名类的实例,该代码非常容易理解,6行代码实现了计算 sqrt(a * 100)。在下一节中,我们将会看到实现单方法接口的更简单的做法。
译者注: 在Java中只有单继承,如果要让一个类赋予新的特性,通常是使用接口来实现,在C++中支持多继承,允许一个子类同时具有多个父类的接口与功能,在其他语言中,让一个类同时具有其他的可复用代码的方法叫做mixin。新的Java 8 的这个特新在编译器实现的角度上来说更加接近Scala的trait。 在C#中也有名为扩展方法的概念,允许给已存在的类型扩展方法,和Java 8的这个在语义上有差别。
二、Lambda 表达式
首先看看在老版本的Java中是如何排列字符串的:
-
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
-
-
-
Collections.sort(names, new Comparator<String>() {
-
@Override
-
public int compare(String a, String b) {
-
return b.compareTo(a);
-
}
-
});
只需要给静态方法 Collections.sort 传入一个List对象以及一个比较器来按指定顺序排列。通常做法都是创建一个匿名的比较器对象然后将其传递给sort方法。
在Java 8 中你就没必要使用这种传统的匿名对象的方式了,Java 8提供了更简洁的语法,lambda表达式:
-
Collections.sort(names, (String a, String b) -> {
-
return b.compareTo(a);
-
});
看到了吧,代码变得更段且更具有可读性,但是实际上还可以写得更短:
复制代码 代码如下:
-
Collections.sort(names, (String a, String b) -> b.compareTo(a));
对于函数体只有一行代码的,你可以去掉大括号{}以及return关键字,但是你还可以写得更短点:
复制代码 代码如下:
-
Collections.sort(names, (a, b) -> b.compareTo(a));
Java编译器可以自动推导出参数类型,所以你可以不用再写一次类型。接下来我们看看lambda表达式还能作出什么更方便的东西来:
三、函数式接口
Lambda表达式是如何在java的类型系统中表示的呢?每一个lambda表达式都对应一个类型,通常是接口类型。而“函数式接口”是指仅仅只包含一个抽象方法的接口,每一个该类型的lambda表达式都会被匹配到这个抽象方法。因为 默认方法 不算抽象方法,所以你也可以给你的函数式接口添加默认方法。
我们可以将lambda表达式当作任意只包含一个抽象方法的接口类型,确保你的接口一定达到这个要求,你只需要给你的接口添加 @FunctionalInterface 注解,编译器如果发现你标注了这个注解的接口有多于一个抽象方法的时候会报错的。
示例如下:
-
@FunctionalInterface
-
interface Converter<F, T> {
-
T convert(F from);
-
}
-
Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
-
Integer converted = converter.convert("123");
-
System.out.println(converted);
需要注意如果@FunctionalInterface如果没有指定,上面的代码也是对的。
译者注 将lambda表达式映射到一个单方法的接口上,这种做法在Java 8之前就有别的语言实现,比如Rhino JavaScript解释器,如果一个函数参数接收一个单方法的接口而你传递的是一个function,Rhino 解释器会自动做一个单接口的实例到function的适配器,典型的应用场景有 org.w3c.dom.events.EventTarget 的addEventListener 第二个参数 EventListener。
四、方法与构造函数引用
前一节中的代码还可以通过静态方法引用来表示:
-
Converter<String, Integer> converter = Integer::valueOf;
-
Integer converted = converter.convert("123");
-
System.out.println(converted);
Java 8 允许你使用 :: 关键字来传递方法或者构造函数引用,上面的代码展示了如何引用一个静态方法,我们也可以引用一个对象的方法:
-
converter = something::startsWith;
-
String converted = converter.convert("Java");
-
System.out.println(converted);
接下来看看构造函数是如何使用::关键字来引用的,首先我们定义一个包含多个构造函数的简单类:
-
class Person {
-
String firstName;
-
String lastName;
-
-
-
Person() {}
-
-
-
Person(String firstName, String lastName) {
-
this.firstName = firstName;
-
this.lastName = lastName;
-
}
-
}
接下来我们指定一个用来创建Person对象的对象工厂接口:
-
interface PersonFactory<P extends Person> {
-
P create(String firstName, String lastName);
-
}
这里我们使用构造函数引用来将他们关联起来,而不是实现一个完整的工厂:
-
PersonFactory<Person> personFactory = Person::new;
-
Person person = personFactory.create("Peter", "Parker");
我们只需要使用 Person::new 来获取Person类构造函数的引用,Java编译器会自动根据PersonFactory.create方法的签名来选择合适的构造函数。
五、Lambda 作用域
在lambda表达式中访问外层作用域和老版本的匿名对象中的方式很相似。你可以直接访问标记了final的外层局部变量,或者实例的字段以及静态变量。
六、访问局部变量
我们可以直接在lambda表达式中访问外层的局部变量:
-
final int num = 1;
-
Converter<Integer, String> stringConverter =
-
(from) -> String.valueOf(from + num);
-
-
-
stringConverter.convert(2);
但是和匿名对象不同的是,这里的变量num可以不用声明为final,该代码同样正确:
-
int num = 1;
-
Converter<Integer, String> stringConverter =
-
(from) -> String.valueOf(from + num);
-
-
-
stringConverter.convert(2);
不过这里的num必须不可被后面的代码修改(即隐性的具有final的语义),例如下面的就无法编译:
-
int num = 1;
-
Converter<Integer, String> stringConverter =
-
(from) -> String.valueOf(from + num);
-
num = 3;
在lambda表达式中试图修改num同样是不允许的。
七、访问对象字段与静态变量
和本地变量不同的是,lambda内部对于实例的字段以及静态变量是即可读又可写。该行为和匿名对象是一致的:
-
class Lambda4 {
-
static int outerStaticNum;
-
int outerNum;
-
-
-
void testScopes() {
-
Converter<Integer, String> stringConverter1 = (from) -> {
-
outerNum = 23;
-
return String.valueOf(from);
-
};
-
-
-
Converter<Integer, String> stringConverter2 = (from) -> {
-
outerStaticNum = 72;
-
return String.valueOf(from);
-
};
-
}
-
}
八、访问接口的默认方法
还记得第一节中的formula例子么,接口Formula定义了一个默认方法sqrt可以直接被formula的实例包括匿名对象访问到,但是在lambda表达式中这个是不行的。
Lambda表达式中是无法访问到默认方法的,以下代码将无法编译:
复制代码 代码如下:
-
Formula formula = (a) -> sqrt( a * 100);
Built-in Functional Interfaces
JDK 1.8 API包含了很多内建的函数式接口,在老Java中常用到的比如Comparator或者Runnable接口,这些接口都增加了@FunctionalInterface注解以便能用在lambda上。
Java 8 API同样还提供了很多全新的函数式接口来让工作更加方便,有一些接口是来自Google Guava库里的,即便你对这些很熟悉了,还是有必要看看这些是如何扩展到lambda上使用的。
Predicate接口
Predicate 接口只有一个参数,返回boolean类型。该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非):
-
Predicate<String> predicate = (s) -> s.length() > 0;
-
predicate.test("foo"); // true
-
predicate.negate().test("foo"); // false
-
Predicate<Boolean> nonNull = Objects::nonNull;
-
Predicate<Boolean> isNull = Objects::isNull;
-
Predicate<String> isEmpty = String::isEmpty;
-
Predicate<String> isNotEmpty = isEmpty.negate();
Function 接口
Function 接口有一个参数并且返回一个结果,并附带了一些可以和其他函数组合的默认方法(compose, andThen):
-
Function<String, Integer> toInteger = Integer::valueOf;
-
Function<String, String> backToString = toInteger.andThen(String::valueOf);
-
-
backToString.apply("123");
Supplier 接口
Supplier 接口返回一个任意范型的值,和Function接口不同的是该接口没有任何参数
复制代码 代码如下:
-
Supplier<Person> personSupplier = Person::new;
-
personSupplier.get();
Consumer 接口
Consumer 接口表示执行在单个参数上的操作。
-
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
-
greeter.accept(new Person("Luke", "Skywalker"));
Comparator 接口
Comparator 是老Java中的经典接口, Java 8在此之上添加了多种默认方法:
-
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
-
Person p1 = new Person("John", "Doe");
-
Person p2 = new Person("Alice", "Wonderland");
-
comparator.compare(p1, p2); // > 0
-
comparator.reversed().compare(p1, p2);
Optional 接口
Optional 不是函数是接口,这是个用来防止NullPointerException异常的辅助类型,这是下一届中将要用到的重要概念,现在先简单的看看这个接口能干什么:
Optional 被定义为一个简单的容器,其值可能是null或者不是null。在Java 8之前一般某个函数应该返回非空对象但是偶尔却可能返回了null,而在Java 8中,不推荐你返回null而是返回Optional。
-
Optional<String> optional = Optional.of("bam");
-
optional.isPresent(); // true
-
optional.get(); // "bam"
-
optional.orElse("fallback"); // "bam"
-
optional.ifPresent((s) -> System.out.println(s.charAt(0)));
Stream 接口
java.util.Stream 表示能应用在一组元素上一次执行的操作序列。Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set, Map不支持。Stream的操作可以串行执行或者并行执行。
首先看看Stream是怎么用,首先创建实例代码的用到的数据List:
-
List<String> stringCollection = new ArrayList<>();
-
stringCollection.add("ddd2");
-
stringCollection.add("aaa2");
-
stringCollection.add("bbb1");
-
stringCollection.add("aaa1");
-
stringCollection.add("bbb3");
-
stringCollection.add("ccc");
-
stringCollection.add("bbb2");
-
stringCollection.add("ddd1");
Java 8扩展了集合类,可以通过 Collection.stream() 或者 Collection.parallelStream() 来创建一个Stream。下面几节将详细解释常用的Stream操作:
Filter 过滤
过滤通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作,所以我们可以在过滤后的结果来应用其他Stream操作(比如forEach)。forEach需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不能在forEach之后来执行其他Stream操作。
复制代码 代码如下:
-
stringCollection
-
.stream()
-
.filter((s) -> s.startsWith("a"))
-
.forEach(System.out::println);
-
-
-
Sort 排序
排序是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序。
-
stringCollection
-
.stream()
-
.sorted()
-
.filter((s) -> s.startsWith("a"))
-
.forEach(System.out::println);
-
-
-
需要注意的是,排序只创建了一个排列好后的Stream,而不会影响原有的数据源,排序之后原数据stringCollection是不会被修改的:
复制代码 代码如下:
-
System.out.println(stringCollection);
-
Map 映射
中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象,下面的示例展示了将字符串转换为大写字符串。你也可以通过map来讲对象转换成其他类型,map返回的Stream类型是根据你map传递进去的函数的返回值决定的。
-
stringCollection
-
.stream()
-
.map(String::toUpperCase)
-
.sorted((a, b) -> b.compareTo(a))
-
.forEach(System.out::println);
Match 匹配
Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。所有的匹配操作都是最终操作,并返回一个boolean类型的值。
-
boolean anyStartsWithA =
-
stringCollection
-
.stream()
-
.anyMatch((s) -> s.startsWith("a"));
-
-
System.out.println(anyStartsWithA); // true
-
-
boolean allStartsWithA =
-
stringCollection
-
.stream()
-
.allMatch((s) -> s.startsWith("a"));
-
-
System.out.println(allStartsWithA); // false
-
-
boolean noneStartsWithZ =
-
stringCollection
-
.stream()
-
.noneMatch((s) -> s.startsWith("z"));
-
-
System.out.println(noneStartsWithZ);
Count 计数
计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。
复制代码 代码如下:
-
long startsWithB =
-
stringCollection
-
.stream()
-
.filter((s) -> s.startsWith("b"))
-
.count();
-
-
System.out.println(startsWithB);
Reduce 规约
这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规越后的结果是通过Optional接口表示的:
-
Optional<String> reduced =
-
stringCollection
-
.stream()
-
.sorted()
-
.reduce((s1, s2) -> s1 + "#" + s2);
-
-
-
reduced.ifPresent(System.out::println);
-
并行Streams
前面提到过Stream有串行和并行两种,串行Stream上的操作是在一个线程中依次完成,而并行Stream则是在多个线程上同时执行。
下面的例子展示了是如何通过并行Stream来提升性能:
首先我们创建一个没有重复元素的大表:
-
int max = 1000000;
-
List<String> values = new ArrayList<>(max);
-
for (int i = 0; i < max; i++) {
-
UUID uuid = UUID.randomUUID();
-
values.add(uuid.toString());
-
}
-
然后我们计算一下排序这个Stream要耗时多久,
-
串行排序:
-
复制代码 代码如下:
-
long t0 = System.nanoTime();
-
-
-
long count = values.stream().sorted().count();
-
System.out.println(count);
-
-
-
long t1 = System.nanoTime();
-
-
-
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
-
System.out.println(String.format("sequential sort took: %d ms", millis));
-
-
-
-
-
并行排序:
-
long t0 = System.nanoTime();
-
-
long count = values.parallelStream().sorted().count();
-
System.out.println(count);
-
-
long t1 = System.nanoTime();
-
-
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
-
System.out.println(String.format("parallel sort took: %d ms", millis));
-
上面两个代码几乎是一样的,但是并行版的快了50%之多,唯一需要做的改动就是将stream()改为parallelStream()。
Map
前面提到过,Map类型不支持stream,不过Map提供了一些新的有用的方法来处理一些日常任务。
-
Map<Integer, String> map = new HashMap<>();
-
for (int i = 0; i < 10; i++) {
-
map.putIfAbsent(i, "val" + i);
-
}
-
map.forEach((id, val) -> System.out.println(val));
以上代码很容易理解, putIfAbsent 不需要我们做额外的存在性检查,而forEach则接收一个Consumer接口来对map里的每一个键值对进行操作。
下面的例子展示了map上的其他有用的函数:
-
map.computeIfPresent(3, (num, val) -> val + num);
-
map.get(3); // val33
-
-
map.computeIfPresent(9, (num, val) -> null);
-
map.containsKey(9); // false
-
-
map.computeIfAbsent(23, num -> "val" + num);
-
map.containsKey(23); // true
-
-
map.computeIfAbsent(3, num -> "bam");
-
map.get(3); // val33
-
-
接下来展示如何在Map里删除一个键值全都匹配的项:
-
复制代码 代码如下:
-
map.remove(3, "val3");
-
map.get(3); // val33
-
-
map.remove(3, "val33");
-
map.get(3);
另外一个有用的方法:
复制代码 代码如下:
map.getOrDefault(42, "not found"); // not found
对Map的元素做合并也变得很容易了:
-
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
-
map.get(9); // val9
-
-
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
-
map.get(9);
Merge做的事情是如果键名不存在则插入,否则则对原键对应的值做合并操作并重新插入到map中。
九、Date API
Java 8 在包java.time下包含了一组全新的时间日期API。新的日期API和开源的Joda-Time库差不多,但又不完全一样,下面的例子展示了这组新API里最重要的一些部分:
Clock 时钟
Clock类提供了访问当前日期和时间的方法,Clock是时区敏感的,可以用来取代 System.currentTimeMillis() 来获取当前的微秒数。某一个特定的时间点也可以使用Instant类来表示,Instant类也可以用来创建老的java.util.Date对象。
复制代码 代码如下:
-
Clock clock = Clock.systemDefaultZone();
-
long millis = clock.millis();
-
Instant instant = clock.instant();
-
Date legacyDate = Date.from(instant);
Timezones 时区
在新API中时区使用ZoneId来表示。时区可以很方便的使用静态方法of来获取到。 时区定义了到UTS时间的时间差,在Instant时间点对象到本地日期对象之间转换的时候是极其重要的。
-
System.out.println(ZoneId.getAvailableZoneIds());
-
// prints all available timezone ids
-
-
ZoneId zone1 = ZoneId.of("Europe/Berlin");
-
ZoneId zone2 = ZoneId.of("Brazil/East");
-
System.out.println(zone1.getRules());
-
System.out.println(zone2.getRules());
-
// ZoneRules[currentStandardOffset=+01:00]
-
LocalTime 本地时间
LocalTime 定义了一个没有时区信息的时间,例如 晚上10点,或者 17:30:15。下面的例子使用前面代码创建的时区创建了两个本地时间。之后比较时间并以小时和分钟为单位计算两个时间的时间差:
-
LocalTime now1 = LocalTime.now(zone1);
-
LocalTime now2 = LocalTime.now(zone2);
-
-
System.out.println(now1.isBefore(now2)); // false
-
-
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
-
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
-
-
System.out.println(hoursBetween); // -3
-
System.out.println(minutesBetween);
LocalTime 提供了多种工厂方法来简化对象的创建,包括解析时间字符串。
-
LocalTime late = LocalTime.of(23, 59, 59);
-
System.out.println(late); // 23:59:59
-
-
DateTimeFormatter germanFormatter =
-
DateTimeFormatter
-
.ofLocalizedTime(FormatStyle.SHORT)
-
.withLocale(Locale.GERMAN);
-
-
LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
-
System.out.println(leetTime);
LocalDate 本地日期
LocalDate 表示了一个确切的日期,比如 2014-03-11。该对象值是不可变的,用起来和LocalTime基本一致。下面的例子展示了如何给Date对象加减天/月/年。另外要注意的是这些对象是不可变的,操作返回的总是一个新实例。
-
LocalDate today = LocalDate.now();
-
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
-
LocalDate yesterday = tomorrow.minusDays(2);
-
-
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
-
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
-
-
System.out.println(dayOfWeek); // FRIDAY
-
从字符串解析一个LocalDate类型和解析LocalTime一样简单:
-
复制代码 代码如下:
-
DateTimeFormatter germanFormatter =
-
DateTimeFormatter
-
.ofLocalizedDate(FormatStyle.MEDIUM)
-
.withLocale(Locale.GERMAN);
-
-
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
-
System.out.println(xmas);
LocalDateTime 本地日期时间
LocalDateTime 同时表示了时间和日期,相当于前两节内容合并到一个对象上了。LocalDateTime和LocalTime还有LocalDate一样,都是不可变的。LocalDateTime提供了一些能访问具体字段的方法。
-
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
-
-
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
-
System.out.println(dayOfWeek); // WEDNESDAY
-
-
Month month = sylvester.getMonth();
-
System.out.println(month); // DECEMBER
-
-
long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
-
System.out.println(minuteOfDay);
只要附加上时区信息,就可以将其转换为一个时间点Instant对象,Instant时间点对象可以很容易的转换为老式的java.util.Date。
-
Instant instant = sylvester
-
.atZone(ZoneId.systemDefault())
-
.toInstant();
-
-
Date legacyDate = Date.from(instant);
-
System.out.println(legacyDate);
格式化LocalDateTime和格式化时间和日期一样的,除了使用预定义好的格式外,我们也可以自己定义格式:
-
DateTimeFormatter formatter =
-
DateTimeFormatter
-
.ofPattern("MMM dd, yyyy - HH:mm");
-
-
-
LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
-
String string = formatter.format(parsed);
-
System.out.println(string);
和java.text.NumberFormat不一样的是新版的DateTimeFormatter是不可变的,所以它是线程安全的。
关于时间日期格式的详细信息:
十、Annotation 注解
在Java 8中支持多重注解了,先看个例子来理解一下是什么意思。
首先定义一个包装类Hints注解用来放置一组具体的Hint注解:
-
@interface Hints {
-
Hint[] value();
-
}
-
-
-
@Repeatable(Hints.class)
-
@interface Hint {
-
String value();
-
}
Java 8允许我们把同一个类型的注解使用多次,只需要给该注解标注一下@Repeatable即可。
例 1: 使用包装类当容器来存多个注解(老方法)
-
@Hints({@Hint("hint1"), @Hint("hint2")})
-
class Person {}
-
例 2:使用多重注解(新方法)
-
复制代码 代码如下:
-
@Hint("hint1")
-
@Hint("hint2")
-
class Person {}
-
第二个例子里java编译器会隐性的帮你定义好@Hints注解,了解这一点有助于你用反射来获取这些信息:
-
复制代码 代码如下:
-
Hint hint = Person.class.getAnnotation(Hint.class);
-
System.out.println(hint); // null
-
-
-
Hints hints1 = Person.class.getAnnotation(Hints.class);
-
System.out.println(hints1.value().length); // 2
-
-
-
Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
-
System.out.println(hints2.length);
即便我们没有在Person类上定义@Hints注解,我们还是可以通过 getAnnotation(Hints.class) 来获取 @Hints注解,更加方便的方法是使用 getAnnotationsByType 可以直接获取到所有的@Hint注解。
另外Java 8的注解还增加到两种新的target上了:
复制代码 代码如下:
-
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
-
@interface MyAnnotation {}
关于Java 8的新特性就写到这了,肯定还有更多的特性等待发掘。JDK 1.8里还有很多很有用的东西,比如Arrays.parallelSort, StampedLock和CompletableFuture等等。