如何通过检查 Java 中内部列表中的值对列表进行排序?

Abr*_*old 2 java java-stream

我有一个像下面这样的课程,

public class Inventory {

   private String name;
   private List<Sample> samples;
}

public class Sample {

   private int count;
   private String date;
}

List<Inventory> inventories;
Run Code Online (Sandbox Code Playgroud)

我已经samples按日期排序了。没关系。但我需要按 Sample 类中的字段inventories对列表进行排序datesamples已经排序了。所以我需要库存按样品日期 DESC 排序。例如,

在该inventories列表中,如果有 3 个数据,

Inventory 1
name = 1
samples has dates of = List of (2021-07-02, 2021-07-03)

Inventory 2
name = 2
samples has dates of = List of (2021-07-02, 2021-09-03, 2021-10-03)

Inventory 3
name = 3
samples has dates of = List of (2021-08-02, 2021-09-03)
Run Code Online (Sandbox Code Playgroud)

所以它应该按日期 DESC 排序,并且在该inventories列表中,它应该具有以下方式的数据,

Inventory 1
Inventory 3
Inventory 2
Run Code Online (Sandbox Code Playgroud)

Art*_*ich 5

您希望根据嵌套集合中的值对集合进行排序。我们该怎么做呢?

您需要实现一个自定义比较器来执行此操作......

static class InventoryComparator implements Comparator<Inventory> {
     public int compare(Inventory i1, Inventory i2) {
         // compare them here like this 
         // a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
         // this can be done by checking the nested lists
     }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样对你的收藏进行排序......

Collections.sort(inventoryList, new InventoryComparator());
Run Code Online (Sandbox Code Playgroud)