var类型
//自动转换类型
var a = 100;
var b = 100.0;
Stream对象
public class App
{
public static void main(String[] args)
{
//java8新特性,除了map对象其他Collection对象可以转化为流
//并且可以支持filter,map等操作
List<String> list = List.of("index1","index2","index3");
list.stream().filter((s)->{return s.startsWith("index3");}).map((s)->{return s.replaceAll("i", "I");}).forEach((s)->System.out.println(s));
//sort操作
//值得注意的是可以使用list.parallelStream().sorted()执行并行排序,以优化排序速度
list = List.of("index100","index1","index10");
list.stream().sorted((a,b)->
{
return a.length() > b.length()?1:-1;
}).forEach((s)->
{
System.out.println(s);
});
}
}
Lambda表达式
public class App
{
public static void main(String[] args)
{
App app = new App();
//如果lambda只有一行,默认返回这一行的结果,例如
//(x)->x+1
//(x)->{return x + 1;}等价
app.function((x)->{System.out.println("inside lambda --- " + x);
return x;});
}
//注意Function模板必须使用包装类Integer而不是int
void function(Function<Integer,Integer> func)
{
func.apply(123);
}
}
默认接口方法
interface Formula {
double calculate(int a);
//实现这个接口的类,如果它没有@override这个方法,则默认实现如下
default double sqrt(int a) {
return Math.sqrt(a);
}
}
方法引用&构造函数引用
//方法引用
Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted); // 123
//构造引用
public class App
{
public static void main(String[] args)
{
Function<Integer,Sample> func = Sample::new;
Sample sample = func.apply(123);
}
}
class Sample
{
public Sample(int a)
{
System.out.println("Constructer function of Sample --- " + a);
}
}
几种内置接口
- Predicates
- Runnable(所有方法默认继承这个接口)
- Functions
- Suppliers
- Consumers
- Comparators
- Optionals