removeIf()是Collection中java 1.8的新方法。作用是按照一定规则过滤集合中的元素。
/**
* Removes a single instance of the specified element from this
* collection, if it is present (optional operation). More formally,
* removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>, if
* this collection contains one or more such elements. Returns
* <tt>true</tt> if this collection contained the specified element (or
* equivalently, if this collection changed as a result of the call).
*
* @param o element to be removed from this collection, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the type of the specified element
* is incompatible with this collection
* (<a href="#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements
* (<a href="#optional-restrictions">optional</a>)
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this collection
*/
boolean remove(Object o);
例:将Song中评分为3和4的剔除
Collection<Song> songList=new ArrayList();
songList.removeIf(Song -> Song.getRating()==3 || Song.getRating()==4);
songList.forEach(s->System.out.println(s));//使用lambda表达式输出结果
removeIf()中的为lambda表达式。
Lambda表达式的语法:
(parameters) -> expression
或
(parameters) ->{ statements; }
例:
// 1. 不需要参数,返回值为 5
() -> 5
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的差值
(x, y) -> x – y
// 4. 接收2个int型整数,返回他们的和
(int x, int y) -> x + y
// 5. 接受一个 string 对象,并在控制台打印
(String s) -> System.out.print(s)
如果不使用lambda表达式,可使用下述方法:
songList.removeIf(new Predicate<Song>() {
public boolean test(Song s) {
return (s.getRating()==3 ||s.getRating()==4);
}
});
songList.forEach(System.out::println); //使用双冒号操作符(double colon operator)
数据源:
Z/z/9/99
W/w/8/88
A/a/1/11
B/b/2/22
C/c/3/33
D/d/4/44
EEEEEEEEEEEEEEEEEEEE/e/5/5555
输出结果:
Z z 9 99
W w 8 88
A a 1 11
B b 2 22
EEEEEEEEEEEEEEEEEEEE e 5 5555
附Song类,toString()已覆盖
class Song{
String title;
String artist;
int rating;
int bpm;
Song(String title,String artist,int rating,int bpm){
this.title=title;
this.artist=artist;
this.rating=rating;
this.bpm=bpm;
}
public String getTitle(){
return title;
}
public String getArtist(){
return artist;
}
public int getRating(){
return rating;
}
public int getBpm(){
return bpm;
}
//覆盖toString方法
public String toString(){
return title+" "+artist+" "+rating+" "+bpm;
}