【问题标题】:Compare with the value of Collection比较Collection的值
【发布时间】:2013-09-25 09:49:12
【问题描述】:

我有Collection<Student> 并希望返回学生列表与过滤器进行比较。 为此,我有以下代码

public Collection<Student> findStudents(String filter) {

    return // ?
}

我的问题是使用 WhereIn/Contains 的返回语句应该是什么?

【问题讨论】:

    标签: java gwt collections where-in


    【解决方案1】:

    使用谷歌番石榴:

    过滤Collection 的学生姓名

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

    过滤Collection&lt;Student&gt;

    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]

    【讨论】:

      【解决方案2】:

      例如这样的(返回新列表,不修改原始列表)

      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 是非常有用的框架。

      【讨论】:

        【解决方案3】:

        试试类似的东西

        public Collection<Student> findStudents(String filter) {
          List<Student> students  = new ArrayList<Student>();
        
           //  filter  data 
           //if criteria match add to   students  
        
            return students;   
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-02
          相关资源
          最近更新 更多