Android java-如何在对象中按特定值对对象列表进行排序

Android java-如何在对象中按特定值对对象列表进行排序,java,android,sorting,collections,comparator,Java,Android,Sorting,Collections,Comparator,我正在尝试按对象中的特定值对对象的arraylist进行排序。做这样一件事的最佳方法是什么。我是否应该将Collections.sort()与某种比较器一起使用 我正在尝试按对象在其中一个变量中的浮点值对对象列表进行排序 编辑: 这就是我到目前为止所做的: public class CustomComparator implements Comparator<Marker> { @Override public int compare(Mark o1, Mark o2

我正在尝试按对象中的特定值对对象的arraylist进行排序。做这样一件事的最佳方法是什么。我是否应该将Collections.sort()与某种比较器一起使用

我正在尝试按对象在其中一个变量中的浮点值对对象列表进行排序

编辑: 这就是我到目前为止所做的:

public class CustomComparator implements Comparator<Marker> {
    @Override
    public int compare(Mark o1, Mark o2) {
        return o1.getDistance().compareTo(o2.getDistance());
    }
}
公共类CustomComparator实现Comparator{
@凌驾
公共整数比较(标记o1,标记o2){
返回o1.getDistance().compareTo(o2.getDistance());
}
}
错误状态:无法对原语类型double调用compareTo(double)


这是因为比较器只能返回特定类型的对象吗?

这里的“Android java”与“普通java”没有任何不同,所以是的
集合。sort()
将是一个好方法。

或者制作一个可以比较对象的文件,或者如果它们都是同一类的实例,您可以使该类实现。然后,您可以使用Collections.sort()进行实际排序。

如果您需要的是默认排序,则应该使用Comparable而不是Comparator

看这里,这可能会有所帮助-

试试这个-

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestSort {

    public static void main(String args[]){

        ToSort toSort1 = new ToSort(new Float(3), "3");
        ToSort toSort2 = new ToSort(new Float(6), "6");
        ToSort toSort3 = new ToSort(new Float(9), "9");
        ToSort toSort4 = new ToSort(new Float(1), "1");
        ToSort toSort5 = new ToSort(new Float(5), "5");
        ToSort toSort6 = new ToSort(new Float(0), "0");
        ToSort toSort7 = new ToSort(new Float(3), "3");
        ToSort toSort8 = new ToSort(new Float(-3), "-3");

        List<ToSort> sortList = new ArrayList<ToSort>();
        sortList.add(toSort1);
        sortList.add(toSort2);
        sortList.add(toSort3);
        sortList.add(toSort4);
        sortList.add(toSort5);
        sortList.add(toSort6);
        sortList.add(toSort7);
        sortList.add(toSort8);

        Collections.sort(sortList);

        for(ToSort toSort : sortList){
            System.out.println(toSort.toString());
        }
    }

}

public class ToSort implements Comparable<ToSort> {

    private Float val;
    private String id;

    public ToSort(Float val, String id){
        this.val = val;
        this.id = id;
    }

    @Override
    public int compareTo(ToSort f) {

        if (val.floatValue() > f.val.floatValue()) {
            return 1;
        }
        else if (val.floatValue() <  f.val.floatValue()) {
            return -1;
        }
        else {
            return 0;
        }

    }

    @Override
    public String toString(){
        return this.id;
    }
}
import java.util.ArrayList;
导入java.util.Collections;
导入java.util.List;
公共类TestSort{
公共静态void main(字符串参数[]){
ToSort toSort1=新ToSort(新浮动(3),“3”);
ToSort toSort2=新ToSort(新浮动(6),“6”);
ToSort toSort3=新ToSort(新浮动(9),“9”);
ToSort toSort4=新ToSort(新浮动(1),“1”);
ToSort toSort5=新ToSort(新浮动(5),“5”);
ToSort toSort6=新ToSort(新浮点(0),“0”);
ToSort ToSort 7=新ToSort(新浮动(3),“3”);
ToSort toSort8=新ToSort(新浮点(-3),“-3”);
List sortList=new ArrayList();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(分类列表);
for(ToSort-ToSort:sortList){
System.out.println(toSort.toString());
}
}
}
公共类ToSort实现了可比较的{
私人浮动增值税;
私有字符串id;
公共ToSort(浮点值,字符串id){
this.val=val;
this.id=id;
}
@凌驾
公共int比较(ToSort f){
如果(val.floatValue()>f.val.floatValue()){
返回1;
}
else if(val.floatValue()
我想这会对你有更好的帮助

Person p = new Person("Bruce", "Willis");
Person p1  = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");

ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);

Collections.sort(list, new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
    }
});
Person p=新人(“布鲁斯”、“威利斯”);
人员p1=新人(“汤姆”、“汉克斯”);
人员p2=新人(“尼古拉斯”、“凯奇”);
人员p3=新人(“约翰”、“特拉沃尔塔”);
ArrayList=新建ArrayList();
增加(p);
列表。添加(p1);
列表。添加(p2);
列表。添加(p3);
Collections.sort(list,newcomparator(){
@凌驾
公共整数比较(对象o1、对象o2){
人p1=(人)o1;
人p2=(人)o2;
返回p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
});

按照此代码对任何ArrayList进行排序

Collections.sort(myList, new Comparator<EmployeeClass>(){
    public int compare(EmployeeClass obj1, EmployeeClass obj2) {
        // ## Ascending order
        return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
        // return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values

        // ## Descending order
        // return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
        // return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
        }
    });
Collections.sort(myList,newcomparator(){
公共整数比较(EmployeeClass obj1,EmployeeClass obj2){
//##升序
返回obj1.firstName.compareTignoreCase(obj2.firstName);//以比较字符串值
//返回Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId));//比较整数值
//##降序
//返回obj2.firstName.compareTignoreCase(obj1.firstName);//以比较字符串值
//返回Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId));//比较整数值
}
});

我有一个列表视图,其中显示了有关所有客户端的信息 我正在使用这个自定义比较器类对客户机名称进行排序。 除了英文字母外,他们还有一些额外的字母 我用这种力量管理(Collator.SECONDARY)

公共类CustomNameComparator实现Comparator{
@凌驾
公共int比较(ClientInfo o1,ClientInfo o2){
Locale=Locale.getDefault();
Collator-Collator=Collator.getInstance(语言环境);
缩孔器固定强度(缩孔器次级);
返回分类比较(o1.title,o2.title);
}
}
主要强度:通常用于表示基本字符之间的差异(例如,“a”<“b”)。这是最大的区别。例如,字典按基本字符划分为不同的部分。
次要强度:字符中的重音被视为次要差异(例如,“as”<“s”<“at”)。字母之间的其他差异也可以视为次要差异,具体取决于语言。当字符串中的任何地方存在主差异时,将忽略次差异。
三级强度:字符的大小写差异以三级强度区分(例如,“ao”<“ao”<“aò”)。此外,字母的变体在第三级强度(如“a”和“a”)上与基本形式不同Ⓐ"). 另一个例子是大假名和小假名之间的差异。当字符串中的任何地方存在主要或次要差异时,将忽略第三级差异。
相同的强度:当所有其他强度相等时,相同的强度用作平分符。将比较每个字符串NFD形式的Unicode代码点值,以防万一没有差异。例如,希伯来语角标记仅在此强度下区分。这
public class DateComparator implements Comparator<Marker> {
    @Override
    public int compare(Mark lhs, Mark rhs) {
        Double distance = Double.valueOf(lhs.getDistance());
        Double distance1 = Double.valueOf(rhs.getDistance());
        if (distance.compareTo(distance1) < 0) {
            return -1;
        } else if (distance.compareTo(distance1) > 0) {
            return 1;
        } else {
            return 0;
        }
    }
}

ArrayList(Marker) arraylist;
Collections.sort(arraylist, new DateComparator());
 public class CustomNameComparator implements Comparator<ClientInfo> {
        @Override

    public int compare(ClientInfo o1, ClientInfo o2) { 

        Locale locale=Locale.getDefault();
        Collator collator = Collator.getInstance(locale);
        collator.setStrength(Collator.SECONDARY);
        return collator.compare(o1.title, o2.title);

    }
}


PRIMARY strength: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. 
SECONDARY strength: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. 
TERTIARY strength: Upper and lower case differences in characters are distinguished at tertiary strength (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary strength (such as "A" and "Ⓐ"). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. 
IDENTICAL strength: When all other strengths are equal, the IDENTICAL strength is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared, just in case there is no difference. For example, Hebrew cantellation marks are only distinguished at this strength. This strength should be used sparingly, as only code point value differences between two strings are an extremely rare occurrence. Using this strength substantially decreases the performance for both comparison and collation key generation APIs. This strength also increases the size of the collation key. 

**Here is a another way to make a rule base sorting if u need it just sharing**

/*      String rules="< å,Å< ä,Ä< a,A< b,B< c,C< d,D< é< e,E< f,F< g,G< h,H< ï< i,I"+"< j,J< k,K< l,L< m,M< n,N< ö,Ö< o,O< p,P< q,Q< r,R"+"< s,S< t,T< ü< u,U< v,V< w,W< x,X< y,Y< z,Z";
        RuleBasedCollator rbc = null;
        try {
            rbc = new RuleBasedCollator(rules);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String myTitles[]={o1.title,o2.title};
        Collections.sort(Arrays.asList(myTitles), rbc);*/
Collections.sort(contactsList, new Comparator<ContactsData>() {

                    @Override
                    public int compare(ContactsData lhs, ContactsData rhs) {

                        char l = Character.toUpperCase(lhs.name.charAt(0));

                        if (l < 'A' || l > 'Z')

                            l += 'Z';

                        char r = Character.toUpperCase(rhs.name.charAt(0));

                        if (r < 'A' || r > 'Z')

                            r += 'Z';

                        String s1 = l + lhs.name.substring(1);

                        String s2 = r + rhs.name.substring(1);

                        return s1.compareTo(s2);

                    }

                });
public class ContactsData {

public String name;
public String id;
public String email;
public String avatar; 
public String connection_type;
public String thumb;
public String small;
public String first_name;
public String last_name;
public String no_of_user;
public int grpIndex;

public ContactsData(String name, String id, String email, String avatar, String connection_type)
{
    this.name = name;
    this.id = id;
    this.email = email;
    this.avatar = avatar;
    this.connection_type = connection_type;

}
}
public static ArrayList<ContactsData> contactsList = new ArrayList<ContactsData>();
public class ToDoModel implements Comparable<ToDoModel> {
    private String id;
    private Date taskDate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Date getTaskDate() {
        return taskDate;
    }

    public void setTaskDate(Date taskDate) {
        this.taskDate = taskDate;
    }

    @Override
    public int compareTo(ToDoModel another) {
        return getTaskDate().compareTo(another.getTaskDate());  
    }
}
for (int i = 0; i < your_array_length; i++) {
    ToDoModel tm = new ToDoModel();
    tm.setId(your_id);
    tm.setTaskDate(your_date);
    mArrayList.add(tm);
}
Collections.sort(toDoList);
Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
      }
 });
Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
      }
 });
fun sortList(list: List<YourCustomPOJOClass?>) {

    //descending
    Collections.sort(
        list
    ) { o1, o2 -> Integer.valueOf(o1!!.intValueXYZ!!).compareTo(o2!!.intValueXYZ!!) }

//    //ascending
//    Collections.sort(
//        list
//    ) { o1, o2 -> Integer.valueOf(o2!!.intValueXYZ!!).compareTo(o1!!.intValueXYZ!!) }
}
sortList(list)