比如現在有一個需求現在有一個List 里面裝Student 對象 我們想找出這個List 對象里面student name=小明的對象 我想很多同學會像以前的我一樣變量List 然后去比較 但是這樣處理畢竟效率不高 所以今天查資料總結下
List<Student> list = new ArrayList<>();
list.add(new Student("name1", 1));
list.add(new Student("name2", 2));
list.add(new Student("name3", 2));
list.add(new Student("name1", 3));
/**
* 方法一
* 利用 Apache Commons Collections 工具類
* 下載地址 http://commons.apache.org/proper/commons-collections/download_collections.cgi
*/
Predicate<Student>predicate = new Predicate<Student>() {
@Override
public boolean evaluate(Student student) {
// TODO Auto-generated method stub
return student.getAge()==2;
}
};
//找出age==2 的對象
List<Student> result = (List<Student>) CollectionUtils.select( list, predicate);
/**
* 方法二
* In java8, using Lambdas and StreamAPI this should be:
* 需要安裝Java8
*/
List<Student> result1 = list.stream()
.filter(item -> item.getName().equals("name1"))
.collect(Collectors.toList());
打印結果
name2 name3 JAVA8------------------ name1 name1
