Pregunta

I have Collection<Student> and want to return the list of student compare with a filter. For this I have following code

public Collection<Student> findStudents(String filter) {

    return // ?
}

My question is what should be the return statement using WhereIn/Contains ?

¿Fue útil?

Solución

Using Google Guava:

Filter a Collection of student names

public Collection<String> findStudents(String filter) {

    Iterable<String> filteredStudents = Iterables.filter(listOfStudentNames, Predicates.containsPattern(filter));
    return Lists.newArrayList(filteredStudents);
}

Filter a 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);

Example:

Iterable<String> filtered = Iterables.filter(Arrays.asList("asdf", "bsdf", "eeadd", "asdfeeee", "123"), Predicates.containsPattern("df"));

filtered now contains [asdf, bsdf, asdfeeee]

Otros consejos

For example something like this (returns new list, not modifying original)

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 Pay attention to "c.P.u1" answer, Google Guava is very useful framework.

Try something like

public Collection<Student> findStudents(String filter) {
  List<Student> students  = new ArrayList<Student>();

   //  filter  data 
   //if criteria match add to   students  

    return students;   
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top