javaspringspring-bootjava-stream

How to groupBy and its count list of items into Map object in Java?


I have a list of Booking and this Booking has field OfficeType as enum as follow

@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;

I get the list of Booking from db, and I need to return to client that list and grouped by Office type and count as:

List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
        Map<OfficeType, Integer> officeTypeMap = new HashMap<>();

How can I stream that list into that map grouping by OfficeType and counts ?


Solution

  • Use lambda expression like below:

    List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
    Map<OfficeType, Integer> officeTypeMap = bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType,Collectors.counting()));