[英]Java 8 - Stream - refer composite objects
我有List<Entry> entries
,具有以下代碼結構,
class Entry {
public Product getProduct() {
return product;
}
}
class Product {
public List<CategoriesData> getCategories() {
return categoriesData;
}
}
class CategoriesData {
public String getName() {
return name;
}
}
我正在查看按 Product - CategoriesData - name 排序(從List<CategoriesData>
的第一個元素)
// Not sure how to refer Name within CategoriesData,
// entries.stream().sorted(
// Comparator.comparing(Entry::getProduct::getCategories::getName))
// .collect(Collectors.toList())
如果您嘗試按第一個類別排序,則需要在比較器中引用它:
List<Entry> sorted =
entries.stream()
.sorted(Comparator.comparing(
e -> e.getProduct().getCategories().get(0).getName())
.collect(Collectors.toList())
編輯:
要回答評論中的問題,要進行二次排序,您必須在Comparator
指定類型:
List<Entry> sorted =
entries.stream()
.sorted(Comparator.comparing(
e -> e.getProduct().getCategories().get(0).getName())
.thenComparing(
(Entry e) -> e.getProduct().getName())
.collect(Collectors.toList())
使用 Mureinik 解決方案,您可以:
Comparator<Entry> entryComperator = Comparator
.comparing(e -> e.getProduct().getCategories().get(0).getName());
List<Entry> sorted =
entries.stream()
.sorted(entryComperator)
.collect(Collectors.toList());
如果列表為空,您可能會考慮更好地訪問列表中的名稱。 你可以像我上面那樣在比較器中隱藏所有這些邏輯
通過@Mureinik 的輸入並進行了一些修改,我最終得到了下面的結果並且它正在運行。 我的要求略有變化,我需要生成地圖。 類別名稱是地圖中的鍵,值將是“條目”列表。
final Map<String, List<Entry>> sortedMap =
data.getEntries().stream()
.sorted(Comparator.comparing(e -> ((Entry) e).getProduct().getCategories().stream().findFirst().get().getName())
.thenComparing(Comparator.comparing(e -> ((Entry) e).getProduct().getName())) )
.collect(Collectors.groupingBy(e -> e.getProduct().getCategories().stream().findFirst().get().getName(),
LinkedHashMap::new, Collectors.toList()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.