0

I have Model class which contains

int rs;
String name;

I want to get rs > 8

ArrayList contains all data

  Collections.sort(arreyList, new Comparator< Model >() {

        public int compare(Model one, Model other) {

    int a = one.getrs();
    int b = other.getrs();
            if (a > 8) {
                if (a > b)
                    return -1;
                else if (a < b)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
    });

but i am getting wrong , and I want to add more filter like > , < , or only that then for string also.

6
  • What are you trying to achieve?. clarify your question. Commented Feb 17, 2016 at 8:28
  • i want from my arreylist get only rs 8 above Commented Feb 17, 2016 at 8:33
  • Your innermost if/else if/else can be replaced simply by Integer.compare(b, a). Commented Feb 17, 2016 at 8:39
  • 1
    Also: Comparators should be anti-symmetrical, so that compare(a, b) == -compare(b, a) - this isn't, because you are only considering a > 8, and not b > 8. Commented Feb 17, 2016 at 8:41
  • 1
    "i want to get rs > 8" Do you mean you want only the elements for which rs > 8? Comparators can't do that - you need to filter the list first. Commented Feb 17, 2016 at 8:42

1 Answer 1

1

If you are using Java 8.

Use something like this.

 List<Model> completeModels = new ArrayList<>();

        completeModels.add(new Model(5, "Joe"));
        completeModels.add(new Model(3, "John"));
        completeModels.add(new Model(8, "Smith"));
        completeModels.add(new Model(10, "Lary"));

        List<Model> filtered = completeModels.stream().filter(u -> u.rs > 8).collect(Collectors.toList());

This will give you a list of Models with rs>8 .

For more reference google 'java 8 filter examples' or go through Stream Oracle Doc.

EDIT

Otherwise(if you are not using java 8) write a method to get the list filtered. I don't know other ways to do this.

eg:

private List<Model> getFilteredList(List<Model> completeModels) {

    List<Model> filtered = new ArrayList<>();

    for (Model m : completeModels) {
        if (m.rs > 8) {
            filtered.add(m);
        }
    }

    return filtered;
}
Sign up to request clarification or add additional context in comments.

1 Comment

java 8 not supported yet in andorid

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.