import java.io.File; import java.io.FileNotFoundException; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; // illustration de l'utilisation de TreeMap sur des données de consommation // électrique en France récupérées sur // https://www.data.gouv.fr/fr/datasets/consommation-quotidienne-brute/ class Date implements Comparable<Date> { final int year, month, day; final int hours, minutes; // format "15/04/2015" et "12:30" Date(String d, String t) { String[] dc = d.split("/"); this.day = Integer.parseInt(dc[0]); this.month = Integer.parseInt(dc[1]); this.year = Integer.parseInt(dc[2]); String[] tc = t.split(":"); this.hours = Integer.parseInt(tc[0]); this.minutes = Integer.parseInt(tc[1]); } @Override public int compareTo(Date that) { if (this.year != that.year) return this.year - that.year; if (this.month != that.month) return this.month - that.month; if (this.day != that.day) return this.day - that.day; if (this.hours != that.hours) return this.hours - that.hours; return this.minutes - that.minutes; } @Override public String toString() { return String.format("%02d", this.day) + "/" + String.format("%02d", this.month) + "/" + this.year + " " + String.format("%02d", this.hours) + ":" + String.format("%02d", this.minutes); } } class Amphi5 { public static void main(String[] args) throws FileNotFoundException { double start = System.currentTimeMillis(); Scanner sc = new Scanner(new File("consommation-quotidienne-brute.csv")); sc.nextLine(); // ignorer les entêtes // on remplit un dictionnaire date -> consommation électrique TreeMap<Date, Integer> map = new TreeMap<>(); while (sc.hasNextLine()) { String s = sc.nextLine(); String[] col = s.split(";"); Date e = new Date(col[1], col[2]); int v = Integer.parseInt(col[8]); map.put(e, v); } sc.close(); System.out.println(map.size() + " entrées entre " + map.firstKey() + " et " + map.lastKey()); // exemple d'opération sur TreeMap : on récupère la consommation // d'octobre 2015 Date from = new Date("01/10/2015", "00:00"); Date to = new Date("31/10/2015", "23:30"); Map<Date, Integer> oct2015 = map.subMap(from, to); System.out.println("octobre 2015 : " + oct2015.size() + " entrées"); int total = 0; for (Entry<Date, Integer> e : oct2015.entrySet()) total += e.getValue(); System.out.println("total : " + total + " MWh"); System.err.println((System.currentTimeMillis() - start) + " ms"); } }