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
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class SortTreeMap implements Comparable<SortTreeMap>{
TreeMap<String, Sess> treeMap= new TreeMap<String, Sess>();
public Sess persone;
public SortTreeMap(){
initialse();
}
@Override
public int compareTo(SortTreeMap o1) {
return this.persone.dateEffet.compareTo(o1.persone.dateEffet);
}
public void initialse(){
Sess p1= new Sess("01/12/2015","01" );
Sess p2= new Sess("01/12/2013","04");
Sess p3= new Sess("01/12/2014","03");
Sess p4= new Sess("28/12/2014","02" );
treeMap.put("3", p1);
treeMap.put("2", p4);
treeMap.put("4", p3);
treeMap.put("1", p2);
}
private void print(Map<String, Sess> sortedMap) {
for (Map.Entry<String, Sess> entree : treeMap.entrySet()) {
System.out.println(entree.getKey()+" ----> "+entree.getValue().dateEffet);
}
}
public void orderByDesc(){
Map<String, Sess> startMap = new HashMap<String, Sess>();
List<Map.Entry<String, Sess>> entryList = new ArrayList<>(startMap.entrySet());
//print(entryList);
// on trie la List, par ordre décroissant
Collections.sort(entryList, (e1, e2) -> e2.getValue().dateEffet.compareTo(e1.getValue().dateEffet));
// on insère les Entry dans l'ordre dans une LinkedHashMap :
Map<String, Sess> sortedMap = new LinkedHashMap<>();
entryList.forEach( entry -> sortedMap.put(entry.getKey(), entry.getValue()) );
// on affiche la map : les données sont dans l'ordre
print(sortedMap);
}
public static void main(String[] args)
{
SortTreeMap sortt= new SortTreeMap();
sortt.orderByDesc();
}
} |
Partager