javacollectionsjava-streamvavr

Undefined method error when using distinctBy returned by stream created from Vavr List.distinctBy


I want to use List.distinctBy to filter lists provided by Vavr.

I added this dependency in my pom.xml

<dependency>
    <groupId>io.vavr</groupId>
    <artifactId>vavr-kotlin</artifactId>
    <version>0.10.0</version>
</dependency>

but when I use it in the code

menuPriceByDayService
        .findAllOrderByUpdateDate(menu, DateUtils.semestralDate(), 26)
        .stream()
        .distinctBy(MenuPriceByDay::getUpdateLocalDate)
        .map(cp -> cp.getUpdateLocalDate())
        .sorted()
        .forEach(System.out::println);

I have a compilation error:

The method distinctBy(MenuPriceByDay::getUpdateLocalDate) is undefined for the type Stream


Solution

  • Well, List.distinctBy is a method on io.vavr.collection.List, and you are trying to call it on a java.util.stream.Stream.

    You can use e.g. StreamEx instead:

    StreamEx.of(
        menuPriceByDayService
            .findAllOrderByUpdateDate(menu, DateUtils.semestralDate(), 26)
            .stream())
        .distinct(MenuPriceByDay::getUpdateLocalDate)
        .map // etc
    

    But for this specific case you really don't need it because you are doing a map by the same function afterwards. So it should be equivalent to

    menuPriceByDayService
        .findAllOrderByUpdateDate(menu, DateUtils.semestralDate(), 26)
        .stream()
        .map(cp -> cp.getUpdateLocalDate())
        .distinct()
        .sorted()
        .forEach(System.out::println);
    

    (assuming getUpdateLocalDate is a pure function).