java - 搜索并排序对象列表

标签 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());


}

帐户名称比较器

public class AccountNameComparator implements Comparator<AccountProfile> {
@Override
public int compare(AccountProfile first, AccountProfile second) {
    return first.getName().compareTo(second.getName());
}

}

列表已排序,但它基于 getname() 我需要使用 getname() 的特定子字符串对列表进行排序

最佳答案

使用指定字符串的位置对该列表进行排序,您可以尝试如下操作:

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

关于java - 搜索并排序对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373927/

相关文章:

android - 以编程方式在 ListView 中设置 TextView 的边距/填充

java - sqlite约束异常主键必须唯一

android - GCM 发件人 ID 不匹配

android-studio - 如何将Android Studio文本选择模式更改为默认?

java - 将 switch case 重构为 HashMap : extra memory usage?

Java:批处理整数

java - CDI Producer 导致 stackoverflow

java - 自动值示例 : error: cannot find symbol class AutoValue_Animal

java - 为什么我无法获得对 Google Play 服务库的依赖?

java - 从 JList 中删除一个元素