搜索和排序对象列表

时间:2016-12-29 05:58:25

标签: java android android-studio

我已经针对在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()我需要使用getname()的特定子字符串对列表进行排序

2 个答案:

答案 0 :(得分:1)

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 :(得分:0)

以上答案略有变化:如下所示

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