Android-java – Comment sortinger une liste d’objects d’une certaine valeur dans l’object

J’essaie de sortinger une liste d’objects par une valeur particulière dans l’object. Quelle serait la meilleure approche pour faire une telle chose? Dois-je utiliser Collections.sort () avec un type de comparateur?

J’essaie de sortinger une liste d’objects par une valeur flottante qu’ils tiennent dans l’une des variables.

EDIT: C’est ce que j’ai jusqu’à présent:

public class CustomComparator implements Comparator { @Override public int compare(Mark o1, Mark o2) { return o1.getDistance().compareTo(o2.getDistance()); } } 

l’erreur indique: Impossible d’invoquer compareTo (double) sur le type de primitive double.

Est-ce parce qu’un comparateur ne peut rien retourner d’autre qu’un certain type?

Vous devez utiliser Comparable plutôt que Comparateur si vous recherchez un sorting par défaut.

Voir ici, cela peut être utile – Quand une classe doit-elle être comparable et / ou un comparateur?

Essaye ça –

 import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TestSort { public static void main(Ssortingng 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 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(sortList); for(ToSort toSort : sortList){ System.out.println(toSort.toSsortingng()); } } } public class ToSort implements Comparable { private Float val; private Ssortingng id; public ToSort(Float val, Ssortingng 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; } } 

Suivez ce code pour sortinger les ArrayList

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

Je pense que cela vous aidera à mieux

 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 list = new ArrayList(); 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()); } }); 

Maintenant, pas besoin de boxer (c.-à-d. Pas besoin de créer OBJECT utilisant new Operator use valueOf insted avec compareTo de Collections.Sort ..)

1) Pour l’ordre croissant

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

1) Pour l’ordre de Deascending

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

“Android-java” n’est nullement différent de “java normal”, donc oui, Collections.sort() serait une bonne approche.

 public class DateComparator implements Comparator { @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; 

Comment utiliser:

 Collections.sort(arraylist, new DateComparator()); 

Vous pouvez comparer deux chaînes en utilisant ceci.

 Collections.sort(contactsList, new Comparator() { @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'; Ssortingng s1 = l + lhs.name.subssortingng(1); Ssortingng s2 = r + rhs.name.subssortingng(1); return s1.compareTo(s2); } }); 

Et maintenant, créez une classe ContactData.

 public class ContactsData { public Ssortingng name; public Ssortingng id; public Ssortingng email; public Ssortingng avatar; public Ssortingng connection_type; public Ssortingng thumb; public Ssortingng small; public Ssortingng first_name; public Ssortingng last_name; public Ssortingng no_of_user; public int grpIndex; public ContactsData(Ssortingng name, Ssortingng id, Ssortingng email, Ssortingng avatar, Ssortingng connection_type) { this.name = name; this.id = id; this.email = email; this.avatar = avatar; this.connection_type = connection_type; } } 

Ici la liste des contacts est la suivante:

 public static ArrayList contactsList = new ArrayList(); 

Créez un Comparator capable de comparer vos objects ou, s’il s’agit de toutes les instances de la même classe, vous pouvez faire en sorte que cette classe mette en œuvre Comparable . Vous pouvez ensuite utiliser Collections.sort () pour effectuer le sorting proprement dit.

J’ai une liste qui affiche les informations sur tous les clients que je sortinge le nom du client en utilisant cette classe de comparateur personnalisée. Ils ont un lerret supplémentaire en dehors des lettres anglaises que je gère avec ce setStrength (Collator.SECONDARY)

  public class CustomNameComparator implements Comparator { @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);*/ 

Classe de modèle:

 public class ToDoModel implements Comparable { private Ssortingng id; private Date taskDate; public Ssortingng getId() { return id; } public void setId(Ssortingng 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()); } } 

Maintenant, définissez les données dans 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); } 

Maintenant, sortingez ArrayList

 Collections.sort(toDoList); 

Résumé: il va sortinger vos données en fonction de la date