Java8几个特性

1、接口的默认方法:
Java8允许我们给接口添加一个非抽象的方法实现,只需要使用default关键字即可,这个叫做扩展,示例如下:

public interface Formula{
	
	 double caculate(int a);
	
     default double sqrt(int a) {
    	 return Math.sqrt(a);
     }
}

在接口中定义了一个默认方法,如果实现接口Formula则可以直接使用方法sqrt看一下下面的使用:

public class Test1 {

	 public static void main(String[] args) {
		 //匿名函数
		Formula formula=new Formula() {
			@Override
			public double caculate(int a) {
				return sqrt(a *100);
			}
		};
		
		formula.caculate(100);
		formula.sqrt(16);
	}
}

2、Lambda无法访问接口的默认方法
接口自定义的default方法可以被匿名对象访问到,或者可以被Formula的实例访问到;但是在lambda表达式中这个是不行的。
Lamdba是访问不到默认方法的

Formula formula = (a) -> sqrt( a * 100);
Built-in Functional Interfaces

3、方法与构造函数引用
定义一个函数式接口

public interface Converter<T,F> {
	F convert(T t);
}
public class Test2 {

	public static void main(String[] args) {
		//Lambda使用
		Converter<String, Integer> converter=(a)->{return Integer.valueOf(a);};
		Integer convert = converter.convert("3333");
		System.out.println("use lambda the result is :"+convert);
		
	     //使用方法和构造函数引用--静态方法引用
		Converter<String, Integer> converter2=Integer::valueOf;
		Integer convert2 = converter2.convert("5555");
		System.out.println("use static function the result is :"+convert2);
		
		使用方法和构造函数引用--对象方法引用
		Test2 test2=new Test2();
		Converter<String, Integer> converter3=test2::getStartWith;
		Integer convert3 =converter3.convert("6666");
		System.out.println("use object function the result is :"+convert3);
	}
	
	
	//构建一个对象的方法
	public  Integer getStartWith(String ss) {
		return Integer.valueOf(ss);
	}
}
use lambda the result is :3333
use static function the result is :5555
use  object  function the result is :6666

构造函数:

public class Person {
	String firstName;
    String lastName;
    
	public Person() {
		super();
	}

	public Person(String firstName, String lastName) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	@Override
	public String toString() {
      return firstName+":"+lastName;
	}
    
}
public interface CreatePersonFactory<P extends Person> {

	P createPerson(String firstName,String lastName);
	
}
public class Test3 {

	public static void main(String[] args) {
		CreatePersonFactory<Person> person1=Person::new;
		Person p1 = person1.createPerson("hello", "world!");
		System.out.println(p1.toString());
	}
}
hello:world!

对于只有一个抽象方法的函数接口,我们可以使用Lambda或者使用“使用方法和构造函数引用–静态方法引用”、“使用方法和构造函数引用–对象方法引用”、“构造函数”四种方法实现,其返回类型为接口类型;

4、Stream接口
java.util.Stream 表示能应用在一组元素上一次执行的操作序列。Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set, Map不支持。

public class Test4 {
	public static void main(String[] args) {
		//初始化一个collection集合队列
		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");
		
		//初始化数据队列
		System.out.println("init list  is :"+stringCollection);
		
		//准备函数式接口
		Test4 test4=new Test4();
		
		//使用过滤-中间操作
		System.out.println("filter operation is going to start!");
		stringCollection
            .stream()
            .filter((s)->s.startsWith("a"))
            .forEach(test4::printForFunction);
		
		
		//使用过滤-排序操作-中间操作
		System.out.println("sorted operation is going to start!");
		stringCollection
		        .stream()
		        .sorted()
		        .filter((s)->s.startsWith("a"))
		        .forEach(test4::printForFunction);
		
		//使用排序-排序map-中间操作	
		System.out.println("map operation is going to start!");
		stringCollection
		        .stream()
		        .map(String::toUpperCase)
		        .sorted((a,b)->b.compareTo(a))
		        .forEach(test4::printForFunction);
		
		//anyMatch-最终操作
		System.out.println("anyMatch operation is going to start!");
		boolean res1=stringCollection
		        .stream()
		        .anyMatch((s)->s.startsWith("a"));
		
		System.out.println("anyMatch operation is going to end and the result is:"+res1);
		        
		//allMatch-最终操作
	   System.out.println("allMatch operation is going to start!");
		boolean res2=stringCollection
		       .stream()
		       .allMatch((s)->s.startsWith("a"));
		System.out.println("allMatch operation is going to end and the result is:"+res2);
		
		//noneMatch-最终操作
		System.out.println("noneMatch operation is going to start!");
		boolean res3=stringCollection
				         .stream()
				         .noneMatch((s)->s.startsWith("z"));
		System.out.println("noneMatch operation is going to end and the result is:"+res3);
		
	
		//count-最终操作
		System.out.println("count operation is going to start!");
		long res4=stringCollection
		     .stream()
		     .filter((a)->a.startsWith("a"))
		     .count();
		System.out.println("count operation is going to end and the result is:"+res4);
		
		
		//reduce-最终操作
		System.out.println("reduce operation is going to start!");
		Optional<String> res5=stringCollection
		        .stream()
		        .sorted((a,b)->b.compareTo(a))
		        .reduce((a,b)->a+"#"+b);
		System.out.println("reduce operation is going to end and the result is:"+res5);	
 	}
	
	
	public void printForFunction(String streamString) {
		StringBuilder buliderBuilder=new StringBuilder();
			 buliderBuilder.append(streamString.toString());
		System.out.println(buliderBuilder.toString());
	}
	
}
init list  is :[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
filter operation is going to start!
aaa2
aaa1
sorted operation is going to start!
aaa1
aaa2
map operation is going to start!
DDD2
DDD1
CCC
BBB3
BBB2
BBB1
AAA2
AAA1
anyMatch operation is going to start!
anyMatch operation is going to end and the result is:true
allMatch operation is going to start!
allMatch operation is going to end and the result is:false
noneMatch operation is going to start!
noneMatch operation is going to end and the result is:true
count operation is going to start!
count operation is going to end and the result is:2
reduce operation is going to start!
reduce operation is going to end and the result is:Optional[ddd2#ddd1#ccc#bbb3#bbb2#bbb1#aaa2#aaa1]

总结:
1、Filter过滤通过一个predicate接口来过滤,只保留符合条件的元素,属于中间操作。
2、Sort排序排序是一个中间操作,返回的是排序好后的Stream,不会影响原有的数据源。
3、Map会将元素根据指定的Function接口来依次将元素转成另外的对象
4、Match匹配,所有的匹配都是最终操作,返回一个boolean类型值。
5、count计数是一个最终的操作,返回Stream中元素的个数,返回值类型是long
6、Reduce这是一个最终的操作,允许通过制定的函数来讲Stream中的多个元素规约为一个元素,规约后的结果通过optional接口表示;

5、串行排序

public class Test5 {
	public static void main(String[] args) {
		int max=1000000;
		List<String> stringCollection=new ArrayList<String>(max);
		
		for(int i=0;i<max;i++) {
			stringCollection.add(UUID.randomUUID().toString());
		}
		
		
		//开始时间
		long start=System.nanoTime();
		
		//使用过滤-排序操作-中间操作
		stringCollection
		        .stream()
		        .sorted()
		        .count();
		long end=System.nanoTime();
		
		System.out.println("使用串行的stream花费的时间是:"+(end-start));
		
		      //开始时间
				long start1=System.nanoTime();
				
				//使用过滤-排序操作-中间操作
				stringCollection
				        .parallelStream()
				        .sorted()
				        .count();
				long end1=System.nanoTime();
				
				System.out.println("使用并行的stream花费的时间是:"+(end1-start1));
 	}
	
}
使用串行的stream花费的时间是:1341475097
使用并行的stream花费的时间是:1123466229
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值