标签: vavr

javaslang元组列表2映射转换

使用javaslang 2.1.0-alpha 将a Stream<Tuple2<T,U>>转换为a 的最惯用的方法是什么Map<T,List<U>>

    // initial stream
    Stream.of(
            Tuple.of("foo", "x"),
            Tuple.of("foo", "y"),
            Tuple.of("bar", "x"),
            Tuple.of("bar", "y"),
            Tuple.of("bar", "z")
    )        
Run Code Online (Sandbox Code Playgroud)

应成为:

    // end result
    HashMap.ofEntries(
            Tuple.of("foo", List.of("x","y")),
            Tuple.of("bar", List.of("x","y","z"))
    );
Run Code Online (Sandbox Code Playgroud)

functional-programming vavr

5
推荐指数
2
解决办法
1190
查看次数

javaslang/Vavr:如何尝试使用资源

这是我的代码片段:

 public static void main(String[] args) {

    Try.of(Main::getLines)
            .onFailure(cause -> log.error("An error has occurred while parsing the file", cause));
}

private static List<Fiche> getLines() {
    return Files.lines(Paths.get("insurance_sample.csv"))
            .skip(1)
            .map(Main::toPojo)
            .filter(fiche -> fiche.getPointLongitude().equals(-81.711777))
            .peek(fiche -> log.info("Fiche added with success {}", fiche))
            .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 try-with-resources 或在“finally”子句中关闭此“Stream”。在这条线上Files.lines(Paths.get("insurance_sample.csv"))

任何人都可以帮助我使用 Vavr 使用 try-with-resources 吗?

java-8 try-with-resources vavr

5
推荐指数
1
解决办法
1755
查看次数

从列表中筛选具有相同成员的对象

我有一个对象列表.该对象如下所示:

public class Slots {
  String slotType;
  Visits visit;
}


public class Visits {
  private long visitCode;
  private String agendaCode;
  private String scheduledTime;
  private String resourceType;
  private String resourceDescription;
  private String visitTypeCode;
  ...
}
Run Code Online (Sandbox Code Playgroud)

我需要找到具有相同元素的元素agendaCode,visitTypeCode并且scheduledTime在我的生活中我无法完成它.

我试过这个:

Set<String> agendas = slotsResponse.getContent().stream()
    .map(Slots::getVisit)
    .map(Visits::getAgendaCode)
    .collect(Collectors.toUnmodifiableSet());

Set<String> visitTypeCode = slotsResponse.getContent().stream()
    .map(Slots::getVisit)
    .map(Visits::getVisitTypeCode)
    .collect(Collectors.toUnmodifiableSet());

Set<String> scheduledTime = slotsResponse.getContent().stream()
    .map(Slots::getVisit)
    .map(Visits::getScheduledTime)
    .collect(Collectors.toUnmodifiableSet());

List<Slots> collect = slotsResponse.getContent().stream()
    .filter(c -> agendas.contains(c.getVisit().getAgendaCode()))
    .filter(c -> visitTypeCode.contains(c.getVisit().getVisitTypeCode()))
    .filter(c -> scheduledTime.contains(c.getVisit().getScheduledTime()))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但它没有做我想的那样.理想情况下,我会有一个列表列表,其中每个子列表是共享相同的Slots对象的列表agendaCode, …

java functional-programming java-stream vavr

5
推荐指数
1
解决办法
108
查看次数

Java Functional Programming: How to convert a if-else ladder inside for loop to functional style?

The expectation is derive 3 lists itemIsBoth, aItems, bItems from the input list items. How to convert code like below to functional style? (I understand this code is clear enough in an imperative style, but I want to know does declarative style really fail to deal with such a simple example). Thanks.

for (Item item: items) {
    if (item.isA() && item.isB()) {
        itemIsBoth.add(item);
    } else if (item.isA()) {
        aItems.add(item);
    } else if (item.isB()){
        bItems.add(item)
    }
}
Run Code Online (Sandbox Code Playgroud)

java functional-programming declarative-programming java-8 vavr

5
推荐指数
1
解决办法
237
查看次数

如何使用 vavr 返回 void 或字符串

我有一个函数,当某些条件不满足时,它应该不返回任何内容( void )或字符串。

我尝试这条线 Either.left(Void)

    private Either<Void,String> processOrReturnErrorMessage(){
        //Do something  and in some case return a message of failed conditions
        return Either.left(Void);
    }
Run Code Online (Sandbox Code Playgroud)

java vavr

5
推荐指数
1
解决办法
5648
查看次数

修复任一 Java Vavr 中的左侧

我想避免:

Either<Error, Employee> processEmployee(Employee e)
Run Code Online (Sandbox Code Playgroud)

并使用:

Result<Employee> processEmployee(Employee e)
Run Code Online (Sandbox Code Playgroud)

其中 left 是固定的:

Result<T> extends Either<Error, T>
Run Code Online (Sandbox Code Playgroud)

有这样的例子吗?

当我尝试这个时,没有任何东西可以为我编译,我被迫实现一个Result<T>我想避免的具体类。

我想这样做的原因是为了简化方法签名和使用这些方法的流代码。

java functional-programming vavr

5
推荐指数
1
解决办法
286
查看次数

来自List的Javaslang/Vavr LinkedHashMap

是否有一种简洁,惯用的方式来创建来自Javaslang/Vavr的订单保留地图ListList.toMap()返回一个普通的HashMap,所以不这样做.我现在拥有的是这样的 -

listOfKeys.foldLeft(
    LinkedHashMap.<Key, Value>.empty(), 
    (m, k) -> m.put(k, valueFor(k))
);
Run Code Online (Sandbox Code Playgroud)

- 但这似乎比必要的更冗长,也可能效率更低.

list linkedhashmap vavr

4
推荐指数
1
解决办法
897
查看次数

类型推断似乎失败vavr的尝试适用于jOOQ的fetchOne()函数

我正在使用vavr和jOOQ,最近出现了两个出色的库,允许我们在常规Java服务器应用程序中使用功能方言.

我试图使用jOOQ,相当于SQL的选择计数(*).

查询以这种方式形成:

 ResultQuery query = dsl.selectCount()
                .from(Tables.SH_PLAYER_REPORT)
                .join(Tables.SH_PLAYERS)
                .on(Tables.SH_PLAYERS.PLAYER_ID.eq(Tables.SH_PLAYER_REPORT.PLAYER_ID))
                .join(Tables.SH_LOCATION)
                .on(Tables.SH_LOCATION.LOCATION_ID.eq(Tables.SH_PLAYERS.LOCATION))
                .and(Tables.SH_PLAYER_REPORT.START_ON.ge(Timestamp.from(fromWhenInUTCInstant)))
                .and(Tables.SH_PLAYER_REPORT.START_ON.le(Timestamp.from(toWhenInUTCInstant)))
                .and(Tables.SH_LOCATION.LOCATION_ID.eq(criteriaAllFieldsTeam.getLocation_id()));
Run Code Online (Sandbox Code Playgroud)

jOOQ的生成器工作得很好,这里没有任何类型不匹配.所以,我想,查询是正确形成的.

然后,我使用vavr的尝试,因此:

Optional<Integer> mayBeCount = Optional.empty();

try (final Connection cn = this.ds.getConnection()) {

    DSLContext dsl = DSL.using(cn, this.dialect);

    Try<Integer> countFromDBAttempted =
               Try
               .of(() -> prepareCountOfGamesPlayedQuery(dsl,criteriaAllFieldsTeam))
               .map(e -> e.fetchOne(0, Integer.class)) // Here's the problem!
               .onFailure(e -> logger.warning(String.format("Count Of Games Played, status=Failed, reason={%s}",e.getMessage())));

           mayBeCount = (countFromDBAttempted.isFailure() ? Optional.empty() : Optional.of(countFromDBAttempted.getOrElse(0)));

  } catch (SQLException ex) {

    logger.warning(
         String.format("DB(jOOQ): Failed, counting games played, using criteria {%s},reason={%s}",criteriaAllFieldsTeam.toString(),ex.getMessage()));
  } …
Run Code Online (Sandbox Code Playgroud)

java mysql jooq vavr

4
推荐指数
1
解决办法
186
查看次数

使用Java 8 Predicate查找"最"正确的值

并感谢您查看我的问题!

我在使用Streams并且按特定顺序应用多个谓词时遇到了一些麻烦.

例如,请考虑以下IntPredicates:

        IntPredicate divisibleByThree = i -> i % 3 == 0;
        IntPredicate divisibleByFour = i -> i % 4 == 0;
        IntPredicate divisibleByFive = i -> i % 5 == 0;
        IntPredicate divisibleByThreeAndFour = divisibleByThree.and(divisibleByFour);
        IntPredicate divisibleByThreeAndFive = divisibleByThree.and(divisibleByFive);
        IntPredicate divisibleByThreeAndFiveAndFour = divisibleByThreeAndFour.and(divisibleByFive);
        //....arbitrary Number of predicates.
Run Code Online (Sandbox Code Playgroud)

第1部分

我已将我遇到的问题转换为"FizzBu​​zz"-esque版本,试图通过将谓词应用于特定顺序的流来找到正确的答案.像这样:

    IntStream.range(1, 100).forEach(i -> {
        //Order matters here!
        if(divisibleByThreeAndFiveAndFour.test(i)){
            System.out.println("Three and four and five");
        } else if(divisibleByThreeAndFour.test(i)){
            System.out.println("Three and four");
        } else if(divisibleByThreeAndFive.test(i)){
            System.out.println("Three and four");
        } else if(divisibleByFive.test(i)){
            System.out.println("Five"); …
Run Code Online (Sandbox Code Playgroud)

java functional-programming java-8 vavr

3
推荐指数
1
解决办法
190
查看次数

如何正确使用VAVR集合是线程安全的?

VAVR集合是"不可变的".

所以,如果我有静态变量,例如,持有所有WebSocket会话,我将如何使用VAVR以使该集合是线程安全的?

例如:

@ServerEndpoint("/actions")
public class DeviceWebSocketServer {

    private static Set<Session> sessions = //???; // how should I initialize this?

    @OnOpen
    public void open(Session session) {
        sessions = sessions.add(session); // is this OK???
    }

    @OnClose
    public void close(Session session) {
        sessions = sessions.remove(session); // is this OK??
    }
}    
Run Code Online (Sandbox Code Playgroud)

java thread-safety vavr

3
推荐指数
1
解决办法
256
查看次数