gpt4 book ai didi

java - 搜索并排序对象列表

转载 作者:行者123 更新时间:2023-12-01 09:04:44 24 4
gpt4 key购买 nike

我已经根据 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com