2016-12-29 179 views
0

我已經篩選了一組對象,針對在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()我需要重新梳理具有的特定子字符串的列表

+3

只要改變比較方法,無論你需要的。 – 2016-12-29 06:02:44

回答

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

String firstName = first.getName()。toLowerCase(); String secoundName = second.getName()。toLowerCase();小變化,它對我有用。謝謝 –

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