我有一個預訂串列,這個預訂的 OfficeType 欄位為列舉,如下所示
@Data
@Entity
@TypeDef(name = "json", typeClass = JsonStringType.class)
public class Booking {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", nullable = false, columnDefinition = "VARCHAR(36)")
private String id;
@Column(name = "office_type")
private OfficeType officeType;
我從 db 獲得了 Booking 的串列,我需要將該串列回傳給客戶,并按Office 型別分組并計為:
List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
Map<OfficeType, Integer> officeTypeMap = new HashMap<>();
如何將該串列按 OfficeType 和計數流式傳輸到該地圖分組中?
uj5u.com熱心網友回復:
使用如下 lambda 運算式:
List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
Map<OfficeType, Integer> officeTypeMap = bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType,Collectors.counting()));
uj5u.com熱心網友回復:
要生成一個Mapof 型別Map<OfficeType,Integer>,您可以使用Collector 的三引數版本toMap(),或者將 CollectorscollectiongAndThen()和groupingBy() collector的組合counting()用作分組的下游。
地圖()
如果您不希望大量元素具有相同的id,則可以使用以下基于三個引數 toMap()的單收集器解決方案:
List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
Map<OfficeType, Integer> officeTypeMap = bookingList.stream()
.collect(Collectors.toMap(
OfficeType::getId,
i -> 1,
Integer::sum
));
性能注意事項:
生成新實體可能會產生少量開銷Integer(因為上面的代碼使用包裝器型別和原語進行操作int)。但是所有Integer值小于的實體128都被 JVM 快取(即它們只會被創建一次,然后將使用相同的參考)。因此,如果大約有一百個相同的元素,那么這個單一的收集器解決方案和下面列出的那個之間id就沒有明顯的區別。
集合gAndThen() & groupingBy()
如果資料量很大,這種方法groupingBy()與下游結合使用可能會更高效。counting()在這種情況下,通過收集器進行累積counting(),使用原始值計算結果值long,會更有優勢。
要轉換Long成Integer,我們可以groupingBy()用collectingAndThen().
List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
Map<OfficeType, Integer> officeTypeMap = bookingList.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(OfficeType::getId, Collectors.counting()),
Long::intValue)
));
uj5u.com熱心網友回復:
解決方案是:
bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));
供參考:Collectors.counting()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/520511.html
