performFiltering:List<>

时间:2018-02-19 07:57:35

标签: java android list arraylist

我只想从List执行过滤搜索,但我只有ArrayList源代码。使用List而不是ArrayList时如何转换它?

以下是我的代码:

 @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();

        //CHECK CONSTRAINT VALIDITY
         if(constraint != null && constraint.length() > 0)
         {
             //CHANGE TO UPPER
             constraint = constraint.toString().toUpperCase();
             //STORE OUR FILTERED ORDER
             ArrayList<OrderModel> filteredOrder = new ArrayList<>();

             for (int i=0; i<filteredOrder.size(); i++) {
                 // CHECK
                 if (filterList.get(i).getCustomerName().toUpperCase().contains(constraint)) {
                     //ADD CUSTOMER TO FILTERED ORDERS
                    filteredOrder.add(filterList.get(i));
                    Log.d("Testing.....","You are here --->" + filteredOrder);
                 }
             }
             results.count = filteredOrder.size();
             results.values = filteredOrder;
         } else {
             results.count = filterList.size();
             results.values = filterList;
         }
        return results;
    }

3 个答案:

答案 0 :(得分:3)

如果替换

,您的代码应该没问题
ArrayList<OrderModel> filteredOrder = new ArrayList<>();

List<OrderModel> filteredOrder = new ArrayList<>();

但要小心,在进口中你必须

import java.util.List;

虽然您只使用add()size(),但它必须有效。

答案 1 :(得分:0)

正如RubioRic所说,我的循环永远不会被执行,因为它的大小是0,而0不大于0.他是对的。我没有注意到这个问题。大拇指!另外,我还将一行替换为:

List<OrderModel> filteredOrder = new ArrayList<>();

答案 2 :(得分:0)

由于我们正在向Java 10发展,请尝试Stream api -

        List<String> list = Arrays.asList("abc","xyz","acd");
        List<String> filteredList = list.stream().filter((element) ->
        {
           return element.startsWith("a");
        }).collect(Collectors.toList());
        System.out.println(filteredList);

您可以在此处插入自己的谓词。