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

Time:10-25

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 ?

CodePudding user response:

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()));

CodePudding user response:

To generate a Map of type Map<OfficeType,Integer> you can either use three-args version of Collector toMap() or a combination of Collectors collectiongAndThen() and groupingBy() collector counting() as a downstream.

toMap()

List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
        
Map<OfficeType, Integer> officeTypeMap = bookingList.stream()
    .collect(Collectors.toMap(
        OfficeType::getId,
        i -> 1,
        Integer::sum
    ));

collectiongAndThen() & groupingBy()

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

CodePudding user response:

The solution would be:

bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));

For reference: Collectors.counting()

  • Related