Sun
Sun

Reputation: 6888

How to filter arraylist based on two values

I have a list of items, where each and every item contains price of product, now i want to filter my arraylist based on user input

I am accepting minimum and maximum price range, and now i would like to show records those are within these price range only.

I am using btnSearch to filter list, to show records between two values, like i want show records those are within these two values;

20000 to 50000

btnSearch.setOnClickListener(new OnClickListener() {

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

I am using below code to filter records based on High to Low price range, and for that i am using below code:

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();
    }
  });

Upvotes: 2

Views: 5406

Answers (5)

Sharp Edge
Sharp Edge

Reputation: 4192

Since Home is your class, and filtering results from ArrayList<Home> you will need to post your Home class, but lets assume Home is some Bean class with a field called price with its respective methods setPrice() and getPrice()

First lets store all the price values in a separate ArrayList<Integer>

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

now sort the above list;

Collections.sort(prices);

now you will have a sorted list, to get range from from 2 values, do something like this:

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

This way you'll have the range of values between the user provided minimum and maximum values.

Upvotes: 1

sanedroid
sanedroid

Reputation: 1036

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

} 
});

and to compare arraylist of objects.. see this link http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

Upvotes: 5

prasad vsv
prasad vsv

Reputation: 1168

First of all, i suggest you to use minHeaps to store data, where, if given with a comparator as in above case, values will be sorted automatically in ascending order and you dont have to sort every time user clicks.

Now, when you have both max and min, you can simply get the index of first element greater than min and last element smaller than max from your minHeap. Now, iterate and get the values within the range


check this out

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);
    }
}

Not satisfied yet?

Upvotes: 0

Stan
Stan

Reputation: 6561

You should not use the Comparator for this since Comparator is for sorting Collections. You should implement Filterable in your adapter class and use Filter instead.

Upvotes: 0

Marek Adamek
Marek Adamek

Reputation: 520

If you're using Java 8 then you can use string to do the filtering. If not then you can simply iterate through collection and select elements that are in price range

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);
}

Upvotes: 1

Related Questions