这可以通过Comparable 接口实现。
我假设Sample 对象按日期排序,Inventory 对象通过比较samples 中的最后一个(Sample 与最新日期)Sample 进行排序,但您可以实现自己的自定义比较 Samples 中覆盖的 compareTo() 方法中的逻辑。
public class Inventory implements Comparable<Inventory> {
private String name;
private List<Sample> samples;
public List<Sample> getSamples() {
return samples;
}
public Inventory(String name, List<Sample> samples) {
this.name = name;
this.samples = samples;
}
@Override
public int compareTo(Inventory inventory) {
Optional<Sample> thisOldestSample = this.getSamples().stream().sorted().reduce((s1, s2) -> s2);
Optional<Sample> thatOldestSample = inventory.getSamples().stream().sorted().reduce((s1, s2) -> s2);
if (thisOldestSample.isPresent() && thatOldestSample.isPresent()) {
return thisOldestSample.get().compareTo(thatOldestSample.get());
} else {
return 0;
}
}
}
public class Sample implements Comparable<Sample> {
private int count;
private String date;
public String getDate() {
return date;
}
public Sample(int count, String date) {
this.count = count;
this.date = date;
}
@Override
public int compareTo(Sample sample) {
return LocalDate.parse(sample.getDate()).isBefore(LocalDate.parse(this.getDate())) ? 1 : -1;
}
}
@Test
void shouldSortInventoriesBasedOnSampleDate() {
Inventory one = new Inventory("1", List.of(new Sample(0, "2021-07-02"), new Sample(1, "2021-07-03")));
Inventory two = new Inventory("2", List.of(new Sample(0, "2021-07-02"), new Sample(1, "2021-09-03"), new Sample(2, "2021-10-03")));
Inventory three = new Inventory("3", List.of(new Sample(0, "2021-08-02"), new Sample(1, "2021-09-03")));
List<Inventory> unsorted = List.of(one, two, three);
List<Inventory> sorted = unsorted.stream().sorted().collect(Collectors.toList());
assertEquals(one, sorted.get(0));
assertEquals(three, sorted.get(1));
assertEquals(two, sorted.get(2));
}