2

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();
    }
  });
7
  • So what problem are you facing ? Any exception, result ? Commented Apr 6, 2015 at 9:38
  • I don't know how to filter list, to show records between two values Commented Apr 6, 2015 at 9:39
  • As far as I understand is, you sort the list but there is no filtering yet. You have to iterate the sorted list and checkif the current element is in the given price range. There is also a filter method provided by Collections2. Commented Apr 6, 2015 at 9:45
  • @Ria can you show me the way, as you understood i have two edit texts in which i am accepting values from user, and want to show list of records Commented Apr 6, 2015 at 9:52
  • @Sun Can you tell me that the arraylist you're using has prices as String or int stored in them ? Commented Apr 6, 2015 at 10:41

5 Answers 5

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

} 
});

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

Sign up to request clarification or add additional context in comments.

8 Comments

what Collections.sort(temp_arraylist); will do here?
check the link I have provided.. I have given an option if in case he wants to sort the list..
@DroidWormNarendra are you aware of collection.sort?, i mean what this method will do?
@DroidWormNarendra - check the link.. he can implement comparable in his setter/getter and use collections.sort to sort arraylist based on object property..
@PoojaGaikwad I don't think OP needs Collection.sort here.
|
1

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

Comments

1

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.

Comments

0

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.

Comments

0

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?

1 Comment

i need solution...can you show me the way, as you understood i have two edit texts in which i am accepting values from user, and want to show list of records

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.