| 失效链接处理 | 
| 
      Java 8 中的炫酷特性和 Java 9 中的新特性 PDF 下载 
	本站整理下载: 
	相关截图: 
![]() 
	主要内容: 
		从行为进行抽象 
	
		“命题: 如何从人员信息的集合里删除所有超过18岁的人?”  
	
		Collection<Person> peoples = ...; 
	
		for (Person p : peoples){ 
	
		if (p.getAge() > 18) 
	
		?? How do we remove this person ??? 
	
		} 
	
		Collection<Person> peoples = ...; 
	
		Iterator<Person> it = peoples.iterator(); 
	
		while (it.hasNext()) { 
	
		Person p = it.next(); 
	
		if (p.getAge() > 18) 
	
		it.remove(); 
	
		} 
	
		Copyright © 2017, Oracle and/or its affiliates. All rights reserved.  
	
		进一步抽象 
	
		interface Predicate<T> {  
	
		boolean test(T t); 
	
		} 
	
		class Collections { 
	
		public static<T>  
	
		void removeMatching(Collection<T> coll,  
	
		Predicate<T> pred) {  
	
		... 
	
		} } 
	
		The API Designer 
	
		Could create methods in the  
	
		collection 
	
		Copyright © 2017, Oracle and/or its affiliates. All rights reserved.  
	
		Collection<Person> peoples = ...; 
	
		Collections.removeMatching(peoples,  
	
		new Predicate<Person>() { 
	
		public boolean test(Person p) { 
	
		return p.getAge() > 18; } } }); 
	
		修改后的实现 But the code to use the new  
	
		method would be bloated 
	
		Copyright © 2017, Oracle and/or its affiliates. All rights reserved.  
	
		使用Java SE 8 
	
		• Interface Collection<E> – removeIf(Predicate<? super E> filter) 
	
		10 
	
		// 简化版 
	
		Collection<Person> peoples = ...; 
	
		peoples.removeIf(p -> p.getAge() > 18); 
 | 
    




    
苏公网安备 32061202001004号


    