我有模型类,其中包含
int rs;
String name;
我想要 rs > 8
ArrayList包含所有数据
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;
}
});
但我错了,我想添加更多过滤器,例如 > 、 < ,或者仅对字符串添加过滤器。
最佳答案
如果您使用的是Java 8。
使用类似的东西。
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());
这将为您提供带有 rs>8
的模型列表。
有关更多引用,请谷歌“java 8 过滤器示例”或浏览 Stream Oracle Doc .
编辑
否则(如果您不使用 java 8)编写一个方法来过滤列表。我不知道还有其他方法可以做到这一点。
例如:
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;
}
关于java - 使用比较器对对象进行 ArrayList 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35451254/