适配器中浮点值的比较器函数

Comparator Function in Adapter on Float values

我与我的数据库的距离越来越远,我想对我的数据进行排序,例如列表中的最短距离应该首先显示在 RecyclerView 中。 我在 m Profile 模型 class 中实现了这样的比较器:

public class Profiles implements Comparator<Profiles>

然后覆盖模型class中的方法:

 @Override
    public int compare(Profiles profiles, Profiles t1) {
        return Float.compare(profiles.getDistance(), t1.getDistance());
    }

现在,在我设置适配器的 class 中,我没有得到应该将哪个列表传递给 Collections.sort(),因为我我给了它 Profile 类型的列表,它给了我这个错误:

no suitable method found for sort(ArrayList<Profiles>) method Collections<T#1>sort(List<T#1>) is not applicable

这就是我在 RecyclerView 中所做的事情 class

reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Profiles profiles = ds.getValue(Profiles.class);
                    profiles.setDistance(distanceFunc());
                    String covid = (String) ds.child("covid_recovered").getValue();
                    String dengue = (String) ds.child("dengue_recovered").getValue();
                    for (DataSnapshot option : ds.child("matched_bloodGroups").getChildren()) {
                        canDonateBG.add(String.valueOf(option.getValue()));
                    }
                    if (canDonateBG.contains(bloodGroup)) {
                        if (recoverey != null) {
                            if (covid.equals(covidRecover)) {
                                list.add(profiles);
                                canDonateBG.clear();
                            } else if (dengue.equals(dengueRecover)) {
                                list.add(profiles);
                                canDonateBG.clear();
                            }
                }
              
                Collections.sort(list);

                donarAdapter = new DonarAdapter(DonarList.this, list);
                recyclerView.setAdapter(donarAdapter);
            }

我应该将哪个列表传递给排序函数,因为它不接受 Profile 类型的列表

根据 docs 有两种排序方法 sort 你调用的 sort(List<T> list) 希望你实现 Comparable 而不是 Comparator如果元素来自像 String class 这样的库,则通过调用 compareTo() 方法以自然顺序对元素进行排序。您正在调用的排序找不到该方法,因为您有 compare() 而不是 compareTo()

Comparator 的是 sort(List<T> list, Comparator<? super T> c) 在你的情况下,如果你只想使用 Comparator,你可以像 Collections.sort(list,this) 而不是 Collections.sort(list) 那样使用它,否则你可以实现 Comparable 并覆盖 compareTo 它是不喜欢它不会使用 Profiles 列表它会使用任何它应该实现正确的接口

我会建议像下面那样做,在这种情况下你不必实现任何接口在java 8 或更高版本

Collections.sort(list,(profiles,t1) -> Float.compare(profiles.getDistance,t1.getDistance()) 

以下java8

Collections.sort(list,new Comparator()<Profiles>{
@Override
public int compare(Profiles profiles,Profiles t1){
   return Float.compare(profiles.getDistance,t1.getDistance);
  });

祝你有美好的一天 Umair Iqbal