J’ai une Collection
générique et j’essaie de déterminer comment je peux sortinger les articles contenus. J’ai essayé quelques trucs, mais je ne peux en obtenir aucun.
Les collections elles-mêmes n’ont pas d’ordre prédéfini, vous devez donc les convertir en java.util.List
. Ensuite, vous pouvez utiliser une forme de java.util.Collections.sort
Collection< T > collection = ...; List< T > list = new ArrayList< T >( collection ); Collections.sort( list ); // or Collections.sort( list, new Comparator< T >( ){...} ); // list now is sorted
Une Collection
n’a pas de commande, donc le fait de vouloir la sortinger n’a pas de sens. Vous pouvez sortinger les instances de List
et les tableaux, et les méthodes à utiliser sont Collections.sort()
et Arrays.sort()
Vous avez deux options de base fournies par java.util.Collections
:
> void sort(List list)
T implements Comparable
et que vous êtes d’accord avec cet ordre naturel void sort(List list, Comparator super T> c)
Comparator
. Selon ce que la Collection
est, vous pouvez également regarder SortedMap
ou SortedMap
.
Si votre object collection est une liste, j’utiliserais la méthode de sorting, telle que proposée dans les autres réponses.
Cependant, s’il ne s’agit pas d’une liste et que vous ne vous souciez pas vraiment du type d’object de collection renvoyé, je pense qu’il est plus rapide de créer un object TreeSet au lieu d’une liste:
TreeSet sortedSet = new TreeSet(myComparator); sortedSet.addAll(myCollectionToBeSorted);
Vous ne pouvez pas si T est tout ce que vous obtenez. Il doit être injecté par le fournisseur:
Collection
ou passer dans le comparateur
Collections.sort(...)
Voici un exemple. ( CompareToBuilder
classe CompareToBuilder
d’Apache pour plus de commodité, bien que cela puisse être fait sans l’utiliser.)
import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.commons.lang.builder.CompareToBuilder; public class Tester { boolean ascending = true; public static void main(Ssortingng args[]) { Tester tester = new Tester(); tester.printValues(); } public void printValues() { List> list = new ArrayList>(); HashMap map = new HashMap(); map.put( "actionId", new Integer(1234) ); map.put( "eventId", new Integer(21) ); map.put( "fromDate", getDate(1) ); map.put( "toDate", getDate(7) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(456) ); map.put( "eventId", new Integer(11) ); map.put( "fromDate", getDate(1) ); map.put( "toDate", getDate(1) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(1234) ); map.put( "eventId", new Integer(20) ); map.put( "fromDate", getDate(4) ); map.put( "toDate", getDate(16) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(1234) ); map.put( "eventId", new Integer(22) ); map.put( "fromDate", getDate(8) ); map.put( "toDate", getDate(11) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(1234) ); map.put( "eventId", new Integer(11) ); map.put( "fromDate", getDate(1) ); map.put( "toDate", getDate(10) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(1234) ); map.put( "eventId", new Integer(11) ); map.put( "fromDate", getDate(4) ); map.put( "toDate", getDate(15) ); list.add(map); map = new HashMap(); map.put( "actionId", new Integer(567) ); map.put( "eventId", new Integer(12) ); map.put( "fromDate", getDate(-1) ); map.put( "toDate", getDate(1) ); list.add(map); System.out.println("\n Before Sorting \n "); for( int j = 0; j < list.size(); j++ ) System.out.println(list.get(j)); Collections.sort( list, new HashMapComparator2() ); System.out.println("\n After Sorting \n "); for( int j = 0; j < list.size(); j++ ) System.out.println(list.get(j)); } public static Date getDate(int days) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, days); return cal.getTime(); } public class HashMapComparator2 implements Comparator { public int compare(Object object1, Object object2) { if( ascending ) { return new CompareToBuilder() .append( ((HashMap)object1).get("actionId"), ((HashMap)object2).get("actionId") ) .append( ((HashMap)object2).get("eventId"), ((HashMap)object1).get("eventId") ) .toComparison(); } else { return new CompareToBuilder() .append( ((HashMap)object2).get("actionId"), ((HashMap)object1).get("actionId") ) .append( ((HashMap)object2).get("eventId"), ((HashMap)object1).get("eventId") ) .toComparison(); } } } }
Si vous travaillez sur un code spécifique et que vous rencontrez des problèmes, vous pouvez publier votre pseudo-code et essayer de vous aider!
En supposant que vous ayez une liste d’objects de type Personne, en utilisant l’expression Lambda, vous pouvez sortinger les noms des utilisateurs par exemple en procédant comme suit:
import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; class Person { private Ssortingng firstName; private Ssortingng lastName; public Person(Ssortingng firstName, Ssortingng lastName){ this.firstName = firstName; this.lastName = lastName; } public Ssortingng getLastName(){ return this.lastName; } public Ssortingng getFirstName(){ return this.firstName; } @Override public Ssortingng toSsortingng(){ return "Person: "+ this.getFirstName() + " " + this.getLastName(); } } class TestSort { public static void main(Ssortingng[] args){ List people = Arrays.asList( new Person("John", "Max"), new Person("Coolio", "Doe"), new Person("Judith", "Dan") ); //Making use of lambda expression to sort the collection people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName())); //Print sorted printPeople(people); } public static void printPeople(List people){ for(Person p : people){ System.out.println(p); } } }