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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章