Reputation: 155
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.
Upvotes: 0
Views: 156
Reputation: 771
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;
}
Upvotes: 1