版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
语法糖让程序更加简洁,有更高的可读性。
一、try-with-resource
Java里,对于文件操作IO流、数据库连接等开销非常昂贵的资源,用完之后必须及时通过close方法将其关闭,否则资源会一直处于打开状态,可能会导致内存泄露等问题。
例子:
/**
* 常规用法
*
* @param file
*/
public void test(File file){
FileInputStream in = null;
try {
in = new FileInputStream(file);
int read = in.read();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 使用try-with-resource后,简化:
/**
* 使用try-with-resource自动关闭资源
*
* @param file
*/
public void test(File file){
try(FileInputStream in = new FileInputStream(file);){
int read = in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
二、lambda表达式和Stream API
Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator。简单来说,它的作用就是通过一系列操作将数据源(集合、数组)转化为想要的结果。
例子:
/**
* lambda和Stream使用
*
* @param file
*/
public void testR(File file){
/*===============lambda 示例===================*/
// 常规用法
new Thread(new Runnable() {
@Override
public void run() {
test(file);
}
});
// 使用lambda
new Thread(() -> test(file));
/*===============Stream 示例===================*/
List<String> list = Arrays.asList(new String[]{"1", "2", "3"});
// 常规取集合中符合某一条件的项
String str;
for (int i = 0; i < list.size(); i++) {
if("2".equals(list.get(i))){
str = list.get(i);
break;
}
}
// 使用Stream取集合中符合某一条件的项
Optional<String> first = list.stream().filter(e -> "2".equals(e)).findFirst();
str = first.get();
}
个人推荐文章:https://www.cnblogs.com/yueshutong/p/9735157.html
三、泛型
泛型,即“参数化类型”。
个人推荐文章:https://blog.csdn.net/u011277123/article/details/81943224
四、方法变长参数
/**
* 可变长参数方法调用
*
*/
public void test(){
int sum = 0;
sum= add(1, 2);
sum= add(1, 2, 3);
sum= add(new int[]{1,2,3,4});
System.out.println("sum和:"+sum);
}
/**
* 可变长参数方法
*
* @param a
* @return
*/
public int add(int... a)
{
int sum = 0;
for (int i = 0; i < a.length; i++)
{
sum += a[i];
}
return sum;
}
五、数值字面量
在java 7中,数值字面量,不管是整数还是浮点数,都允许在数字之间插入任意多个下划线。这些下划线不会对字面量的数值产生影响,目的就是方便阅读。
public class Test {
public static void main(String... args) {
int i = 10_000;
System.out.println(i);
}
}
编译后:
public class Test {
public static void main(String... args) {
int i = 10000;
System.out.println(i);
}
}