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
| public class Demo {
public static void main(String[] args) {
List<VoyageBean> list = Arrays.asList(
new VoyageBean("FAT_1", LocalDate.of(2016, 1, 1), 1000),
new VoyageBean("FAT_1", LocalDate.of(2016, 2, 2), 1500),
new VoyageBean("FAT_1", LocalDate.of(2016, 3, 3), 2000),
new VoyageBean("FAT_2", LocalDate.of(2016, 1, 1), 1000),
new VoyageBean("FAT_2", LocalDate.of(2016, 1, 1), 1010),
new VoyageBean("FAT_2", LocalDate.of(2016, 3, 3), 2000),
new VoyageBean("FAT_3", LocalDate.of(2016, 1, 1), 1000),
new VoyageBean("FAT_3", LocalDate.of(2016, 1, 1), 1000),
new VoyageBean("FAT_3", LocalDate.of(2016, 3, 3), 2000)
);
List<VoyageBean> result = list.stream()
.collect(
Collectors.groupingBy(VoyageBean::getFat, // groupement sur l'identifiant
Collectors.reducing(
BinaryOperator.minBy(
Comparator.comparing(VoyageBean::getDate) // réduction sur la date la plus ancienne
.thenComparing(VoyageBean::getDistance)) // réduction de la distance la plus courte
)
))
.values() // on veut une liste, et la réduction donne des Optional<VoyageBean>, on remap donc sur des VoyageBean
.stream()
.map(v-> v.orElse(null)) // on remap sur des VoyageBean
.sorted(Comparator.comparing(VoyageBean::getFat))
.collect(Collectors.toList());
System.out.println(result);
}
public static class VoyageBean {
private String fat;
private LocalDate date;
private long distance;
public VoyageBean(String fat, LocalDate date, long distance) {
this.fat=fat;
this.date=date;
this.distance=distance;
}
public String getFat() {
return fat;
}
public LocalDate getDate() {
return date;
}
public long getDistance() {
return distance;
}
@Override
public String toString() {
return fat+" "+date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))+" "+distance+"km";
}
}
} |
Partager