1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class Test {
private static Collator COLLATOR = Collator.getInstance(Locale.FRENCH);
private List<Personne> liste1 = new ArrayList<Personne>();
public static void main(String[] args) {
new Test();
}
public Test() {
this.liste1.add(new Personne(6, "Naimare", "jean"));
this.liste1.add(new Personne(2, "martin", "anne"));
this.liste1.add(new Personne(4, "martinet", "alain"));
this.liste1.add(new Personne(3, "andre", "gilles"));
this.liste1.add(new Personne(5, "Zachari", "philippe"));
this.liste1.add(new Personne(1, "dupont", "jean"));
this.liste1.add(new Personne(5, "martin", "jean"));
Collections.sort(this.liste1, new PersonneComparator(CompareType.NOM));
System.out.println("Par nom");
System.out.println("-------");
for (Personne p : this.liste1) {
System.out.print("{");
System.out.printf("%10s", p.getNom());
System.out.print(", ");
System.out.printf("%10s", p.getPrenom());
System.out.println(" }");
}
Collections.sort(this.liste1, new PersonneComparator(CompareType.PRENOM));
System.out.println("\nPar prénom");
System.out.println("-----------");
for (Personne p : this.liste1) {
System.out.print("{");
System.out.printf("%10s", p.getPrenom());
System.out.print(", ");
System.out.printf("%10s", p.getNom());
System.out.println(" }");
}
}
public class Personne {
private long id = 0;
private String nom = null;
private String prenom = null;
public Personne(long id, String nom, String prenom) {
super();
this.id = id;
this.nom = nom;
this.prenom = prenom;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return this.prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
public class PersonneComparator implements Comparator<Personne> {
private CompareType type;
public PersonneComparator(CompareType t) {
this.type = t;
}
@Override
public int compare(Personne p1, Personne p2) {
if (this.type == CompareType.NOM) {
int c = COLLATOR.compare(p1.getNom(), p2.getNom());
if (c == 0) {
return COLLATOR.compare(p1.getPrenom(), p2.getPrenom());
} else {
return c;
}
} else {
int c = COLLATOR.compare(p1.getPrenom(), p2.getPrenom());
if (c == 0) {
return COLLATOR.compare(p1.getNom(), p2.getNom());
} else {
return c;
}
}
}
}
public enum CompareType {
NOM,
PRENOM;
}
} |
Partager