我有Collection<Student>
并希望返回与过滤器比较的学生列表。
为此,我有以下代码
public Collection<Student> findStudents(String filter) {
return // ?
}
我的问题是什么应该是使用WhereIn / Contains的返回语句?
答案 0 :(得分:3)
使用Google Guava:
过滤Collection
个学生姓名
public Collection<String> findStudents(String filter) {
Iterable<String> filteredStudents = Iterables.filter(listOfStudentNames, Predicates.containsPattern(filter));
return Lists.newArrayList(filteredStudents);
}
过滤Collection<Student>
public Collection<Student> findStudents(String filter) {
Iterable<Student> filteredStudents = Iterables.filter(listOfStudents, new Predicate<Student>() {
@Override
public boolean apply(Student student) {
return student.getName().contains(filter);
}
}
}
return Lists.newArrayList(filteredStudents);
示例:
Iterable<String> filtered = Iterables.filter(Arrays.asList("asdf", "bsdf", "eeadd", "asdfeeee", "123"), Predicates.containsPattern("df"));
filtered
现在包含[asdf, bsdf, asdfeeee]
答案 1 :(得分:1)
例如类似的东西(返回新列表,不修改原始列表)
public Collection<Student> findStudents(List<Student> orgininalList, String filter) {
List<Student> filteredList = new ArrayList<Student>();
for(Student s : originalList) {
if(s.getName().contains(filter)) {
filterdList.add(s);
}
}
return filteredList;
}
P.S注意“c.P.u1”的答案,Google Guava是非常有用的框架。
答案 2 :(得分:0)
尝试类似
的内容public Collection<Student> findStudents(String filter) {
List<Student> students = new ArrayList<Student>();
// filter data
//if criteria match add to students
return students;
}