Search code examples
javajava-stream

Lamba function not working in java groupingBy method by Collectors interface


I created this first map where the key is the String slot of a gym course and the value is the number of participants for each slot. Now I want to create a second map with basically keys and values inverted, so the key will be the number of participants and the values will be the list of slots which have that number of participants.I wrote this code but I have no idea why it is complaining with my lambda functions in the second java stream... I literally lost an hour thinking about it and I would really appreciate any help!Thanks in advance, here's the code:

    public SortedMap<Integer, List<String>> slotsPerNofParticipants(String gymnname) throws FitException{
        // map with key = Slot   value = number of participants for the slot
        Map<String, Long> map = this.reservationsColl.stream().filter(r->r.getGym().getName().equals(gymnname))
        .collect(Collectors.groupingBy(r->r.getDayslotStringFormat(),
                Collectors.counting() ));
        // map with key = number of participants  value = list of slot with that number of participants
        Map<Integer,List<String>> res = map.entrySet().stream()
                .collect(Collectors.groupingBy(
                        e->e.getValue.intValue(),
                        Collectors.mapping(e->e.getKey, Collectors.toList() ) ) );
        
        return null;
    }

As you can see I tried to use the lambda function to convert the value of the first map (Long) into an Integer type key... I don't know why it is complaining about the lambda functions... The error messages are: "getKey cannot be resolved or is not a field" "getValue cannot be resolved or is not a field"


Solution

  • Here is one problem. You have some typos.

    • getValue should be getValue()
    • getKey should be getKey()

    The uncorrected code

    Map<Integer,List<String>> res = map.entrySet().stream()
                    .collect(Collectors.groupingBy(
                            e->e.getValue.intValue(),
                            Collectors.mapping(e->e.getKey, Collectors.toList() ) ) );
    

    Any other problems resulting from your objects should include the declaration of the classes and some sample data.

    Input and expected output should be included.