如何根据两个值过滤arraylist

时间:2015-04-06 09:35:36

标签: java android arraylist

我有一个项目列表,其中每个项目都包含产品价格,现在我想根据用户输入过滤我的arraylist

我接受最低和最高价格范围,现在我想显示仅在这些价格范围内的记录。

我正在使用btnSearch来过滤列表,以显示两个值之间的记录,比如我想要显示那些在这两个值内的记录;

20000至50000

btnSearch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                editMin.getText().toString();
                editMax.getText().toString();
            }
        });

我使用以下代码根据高价到低价范围过滤记录,为此我使用下面的代码:

btnHTL.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

Collections.sort(arrayList, new Comparator<Home>() {

    @Override
    public int compare(Home arg1, Home arg2) {
    // TODO Auto-generated method stub
        Integer obj1 = new Integer(arg1.getPrice().replace(",", ""));
        Integer obj2 = new Integer(arg2.getPrice().replace(",", ""));
        return (obj2).compareTo(obj1);
     }
   });

   for (int i = 0; i < arrayList.size(); i++) {
      System.out.println("HTL:--" + arrayList.get(i).getPrice());                    
    }
      adapter.notifyDataSetChanged();
    }
  });

5 个答案:

答案 0 :(得分:5)

    btnSearch.setOnClickListener(new OnClickListener() { 

@Override 
public void onClick(View v) { 
// TODO Auto-generated method stub 

Integer objMin = new Integer(editMin.getText().toString()); 
Log.d("min:", String.valueOf(objMin)); 
Integer objMax = new Integer(editMax.getText().toString()); 
Log.d("max:", String.valueOf(objMax)); 

ArrayList<Home> temp_arraylist = new ArrayList<Home>(); 

for (int i = 0; i < arrayList.size(); i++) { 

int price = (Integer.parseInt(arrayList.get(i).getPrice().replace(",", ""))); 

if(price >= objMin && price <= objMax){ 
temp_arraylist.add(arrayList.get(i)); 
} 

} 

adapter = new HomeAdapter(getApplicationContext(), R.layout.adapter_home, temp_arraylist); 
listview.setAdapter(adapter); 

} 
});

并比较对象的arraylist ..请参阅此链接http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

答案 1 :(得分:1)

由于Home是您的类,并且过滤ArrayList<Home>的结果,您需要发布您的Home类,但我们假设Home是一个带有字段的Bean类使用各自的方法pricesetPrice()

调用getPrice()

首先,我们可以将所有price值存储在单独的ArrayList<Integer>

List<Integer> prices = new ArrayList<Integer>();
for(Home m : arraylist){
   prices.add(m.getPrice());
}

现在对上面的列表进行排序;

Collections.sort(prices);

现在你将有一个排序列表,从2个值中得到范围,做这样的事情:

int minByUser = 28000;
int maxByUser = 40000;

List<Integer> temporary = new ArrayList<>();


    if(prices.contains(minByUser) && prices.contains(maxByUser)){
       prices.subList(prices.indexOf(minByUser), prices.indexOf(maxByUser)); // display this sublist
    }

    else{

        for(int num : prices){
            if(num >= minByUser && num <= maxByUser){ 
            temporary.add(num); 
            } 

        }
    }

    System.out.print(temporary); // for android you can Log to see the results before using the sublist in your ListView

通过这种方式,您可以获得用户提供的最小值和最大值之间的值范围。

答案 2 :(得分:0)

首先,我建议您使用minHeaps存储数据,如果使用比较器给出,如上所述,值将按升序自动排序,您不必在每次用户点击时排序。

现在,当你同时拥有max和min时,你可以简单地从minHeap获得第一个元素的索引大于min并且最后一个元素小于max。现在,迭代并获取范围

内的值

检查出来

String min = editMin.getText().toString();
String max = editMax.getText().toString();

PriorityQueue<Home> queue = 
        new PriorityQueue<Home>(10, comparator);

//To get the range,
Book bookArray[] = new Book[queue.size()];
int minIndex,maxIndex;
for(int i=0;i<queue.size();++i){
     if(bookArray[i] < min ){

         continue;
     }  
     minIndex= i;
     break;  
}
for(int i=minIndex;i<queue.size();++i){
     if(bookArray[i] < max ){

         continue;
     }  
     maxIndex= i-1;
     break;  
}
ArrayList toUseArray = new ArrayList<Book>[maxIndex-minIndex+1];
for(int i = minIndex; i< maxIndex +1;++i){
    toUseArray.add(bookArray[i]);
}

//Now you have all the elements within that range


// Have this comparator class as an inner class or a separate class.
public class comparator implements Comparator<String>
{
    @Override
    public int compare(Home arg1, Home arg2)
    {
        // Assume neither Home object is null.
        Integer obj1 = new Integer(arg1.getPrice().replace(",", ""));
        Integer obj2 = new Integer(arg2.getPrice().replace(",", ""));
        return (obj2).compareTo(obj1);
    }
}

还不满意吗?

答案 3 :(得分:0)

如果您使用的是Java 8,则可以使用字符串进行过滤。如果没有,那么您可以简单地遍历集合并选择价格范围

的元素
List<Home> homes = ...
int from = 3, to = 6;

// JAVA 8
List<Integer> filtered = homes.stream().filter(x -> {
    int price = new Integer(x.getPrice().replace(",", ""));
    return price >= from && price <= to;
}).collect(Collectors.toList());

// Simple filtering with for loop
List<Integer> filtered = new ArrayList<>();
for (Home home : homes) {
    int price = new Integer(home.getPrice().replace(",", ""));
    if (price >= from && price <= to)
        filtered.add(x);
}

答案 4 :(得分:0)

由于Comparator用于对集合进行排序,因此不应使用Comparator。而是You should implement Filterable in your adapter class and use Filter