Android-java-如何按对象内的某个值对对象列表进行排序
Posted
技术标签:
【中文标题】Android-java-如何按对象内的某个值对对象列表进行排序【英文标题】:Android-java- How to sort a list of objects by a certain value within the object 【发布时间】:2012-02-24 23:07:27 【问题描述】:我试图通过对象中的特定值对对象数组列表进行排序。做这种事情的最佳方法是什么。我应该将 Collections.sort() 与某种比较器一起使用吗?
我正在尝试按对象在其中一个变量中保存的浮点值对对象列表进行排序。
编辑: 这是我目前所拥有的:
public class CustomComparator implements Comparator<Marker>
@Override
public int compare(Mark o1, Mark o2)
return o1.getDistance().compareTo(o2.getDistance());
错误状态:无法在基本类型 double 上调用 compareTo(double)。
是不是因为比较器不能返回某种类型以外的任何东西?
【问题讨论】:
“我应该将 Collections.sort() 与某种比较器一起使用吗?” 是的,听起来是个好主意 我不知道这是否重要,但列表中的对象数量将高达 80。这就是为什么我对使用比较器感到困惑,因为它只比较一次有两个值。 这就是排序的工作原理。首先将一项添加到列表中。下次添加时;这应该在列表中的当前之前还是之后。添加第三项时与列表中的第一项进行比较,如果之后则与下一项进行比较。以此类推。 【参考方案1】:按照此代码对任何 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
);
【讨论】:
这应该是最佳答案! 简单而出色的答案,兄弟:) 简单又小巧..谢谢! 这看起来很干净。谢谢。以及提供的提示一加。 int compare 可以替换为:return Integer.compare(obj1.empId, obj2.empId);【参考方案2】:如果您要查找默认排序,则应使用 Comparable 而不是 Comparator。
看这里,这可能会有所帮助 - When should a class be Comparable and/or 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;
【讨论】:
嘿,谢谢你的链接 :) 我从一种语言来回切换到另一种语言,所以我总是错过一些东西 :p 你知道它是怎么回事......万事通,但一个无主大声笑【参考方案3】:我认为这会更好地帮助你
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());
);
【讨论】:
【参考方案4】:现在无需装箱(即无需使用新运算符创建 OBJECT
使用 valueOf 与 Collections.Sort 的 compareTo 相结合..)
1)升序
Collections.sort(temp, new Comparator<XYZBean>()
@Override
public int compare(XYZBean lhs, XYZBean rhs)
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
);
1)对于降序
Collections.sort(temp, new Comparator<XYZBean>()
@Override
public int compare(XYZBean lhs, XYZBean rhs)
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
);
【讨论】:
【参考方案5】:对 Kotlin 来说非常简单!
listToBeSorted.sortBy it.distance
【讨论】:
【参考方案6】:你可以使用这个来比较两个字符串。
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);
);
现在创建一个 ContactData 类。
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>();
【讨论】:
这会将名称从数字开始(即 1gbfilename)放在底部。如何将它们放在顶部?【参考方案7】:对于Kotlin,可以使用这个函数
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!!)
只需在您的activity
或fragment
中调用它
sortList(list)
【讨论】:
【参考方案8】:“android-java”在这里与“普通 java”没有任何不同,所以是的,Collections.sort()
将是一个好方法。
【讨论】:
但是如何让它按对象中的值排序。这就是我坚持的。【参考方案9】: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());
【讨论】:
【参考方案10】:人物模型类
class Person
int id;
String name;
String fatherName;
public Person(int id, String name, String fatherName)
this.id = id;
this.name = name;
this.fatherName = fatherName;
排序
class SORT_BY_ID implements Comparator<Person>
public int compare(Person a, Person b)
return a.id - b.id;
用法
ArrayList<Person> personArrayList = new ArrayList<Person>();
personArrayList.add(new Person(111, "bb", "oakla"));
personArrayList.add(new Person(131, "aa", "fast"));
personArrayList.add(new Person(121, "cccc", "paokla"));
System.out.println("Before Sorted Array list of PErson");
for (int i=0; i<personArrayList.size(); i++)
System.out.println(personArrayList.get(i));
Collections.sort(personArrayList, new SORT_BY_ID());
System.out.println("After Sorted ");
for (int i=0; i<personArrayList.size(); i++)
System.out.println(personArrayList.get(i));
【讨论】:
已经给出了相同的答案。您还可以看到不同的方法。【参考方案11】:要么创建一个Comparator
来比较你的对象,或者如果它们都是同一个类的实例,你可以让那个类实现Comparable
。然后,您可以使用 Collections.sort() 进行实际排序。
【讨论】:
我继续在我的类中实现了 Comparable,但是当我需要对其进行排序时,我创建了一个在列表上调用 sort 的方法,但是如何按对象中的值对其进行排序?compareTo()
-方法是您进行比较的地方。用谷歌搜索了几个关于如何使用它的详细示例,这里是其中之一:javadeveloper.co.in/java-example/java-comparable-example.html
我设置了一个与示例类似的方法,但是我收到一条错误消息,指出我不能在演员替身上使用 compareTo。似乎出于某种原因,我不喜欢做什么。无法在基本类型 double 上调用 compareTo(double)。我会在上面添加我的代码以显示我的意思【参考方案12】:
模型类:
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());
现在在 ArrayList 中设置数据
for (int i = 0; i < your_array_length; i++)
ToDoModel tm = new ToDoModel();
tm.setId(your_id);
tm.setTaskDate(your_date);
mArrayList.add(tm);
现在对 ArrayList 进行排序
Collections.sort(toDoList);
总结:它将按日期对您的数据进行排序
【讨论】:
【参考方案13】:我正在使用此代码:
Collections.sort(groupMemberList, new Comparator<GroupMember>()
@Override
public int compare(GroupMember o1, GroupMember o2)
return Long.valueOf(o2.getStatus()).compareTo(Long.valueOf(o1.getStatus()));
@Override
public boolean equals(Object obj)
return false;
);
【讨论】:
【参考方案14】:我有一个显示所有客户信息的列表视图 我正在使用这个自定义比较器类对客户名称进行排序。 除了英文字母之外,他们还有一些额外的 lerret 我正在使用这个 setStrength(Collator.SECONDARY)
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);*/
【讨论】:
以上是关于Android-java-如何按对象内的某个值对对象列表进行排序的主要内容,如果未能解决你的问题,请参考以下文章