对象的搜索和排序列表
问题描述:
我已经筛选了一组对象,针对在EditText
中输入的特定字符串,现在我需要使用指定字符串的位置对该列表进行排序,我该怎么做?对象的搜索和排序列表
我已经做到了这一点
过滤功能
public void setFilter(String query) {
visibleList = new ArrayList<>();
query = query.toLowerCase(Locale.getDefault());
for (AccountProfile accountProfile : accountProfileList) {
if (accountProfile.getName().toLowerCase(Locale.getDefault())
.contains(query))
visibleList.add(accountProfile);
}
Collections.sort(visibleList, new AccountNameComparator());
}
AccountNameComparator
public class AccountNameComparator implements Comparator<AccountProfile> {
@Override
public int compare(AccountProfile first, AccountProfile second) {
return first.getName().compareTo(second.getName());
}
}
列表排序,但它是基于getname()
我需要重新梳理具有的特定子字符串的列表
答
要sort that list with the position of the specified string
,你可以尝试这样的事:
public class AccountNameComparator implements Comparator<AccountProfile> {
private final String query;
public AccountNameComparator(String query) {
this.query = query;
}
@Override
public int compare(AccountProfile first, AccountProfile second) {
Integer f = first.getName().indexOf(this.query);
Integer s = second.getName().indexOf(this.query);
return f.compareTo(s);
}
}
+1
String firstName = first.getName()。toLowerCase(); String secoundName = second.getName()。toLowerCase();小变化,它对我有用。谢谢 –
答
有一个在上面的回答略有变化:像下面
public class AccountNameComparator implements Comparator<AccountProfile> {
private final String query;
public AccoluntNameSortComparator(String query) {
this.query = query;
}
@Override
public int compare(AccountProfile first, AccountProfile second) {
String firstName = first.getName().toLowerCase();
String secoundName = second.getName().toLowerCase();
query = query.toLowerCase();
Integer f = firstName.indexOf(query);
Integer s = secoundName.indexOf(query);
return f.compareTo(s);
}
}
只要改变比较方法,无论你需要的。 – 2016-12-29 06:02:44