有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java选项:返回值或执行某些操作并继续循环

在一个循环中,我有类似的代码

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);

        if(item == null) {
            Log.error("No item by id");
            continue;
        }

        // bla bla bla
    }

使用Optionals重写此文件的最佳方法是什么

我试图重写,并希望使用ifPresentOrElse使代码更短,但方法ifPresentOrElse()是编写的

When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.

因此,如果有值,我就不能返回它。 有什么建议吗

多谢各位

更新:很抱歉,我忘了提到我需要可选的解决方案,因为存储库函数getById已经更改,它返回可选的结果


共 (4) 个答案

  1. # 1 楼答案

    使用Optional的一个很好的用例是通过避免不必要的空检查来编写整洁的代码。 因此,在代码中有一个地方可以使用可选选项-

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);
    
        Item item_notNull = Optional.ofNullable(item).orElse(<deafult instance of Item>);
        // now do anything with item_notNull, it'll never be null
        // bla bla bla
    }
    

    上述代码的限制是,如果项为null,则不会收到通知。如果需要,可以使用以下代码

    for (Id id : ids) {
        Optional<Item> item = Optional.ofNullable(Repo.findbyId(id));
    
    
        if (item.isPresent()) {
                System.out.println("No item by id");
                continue;
            }else{
                //do something
            }
    
    
        // bla bla bla
    }
    
  2. # 2 楼答案

    for (Id id : ids) {
        Optional<Item> item = Optional.ofNullable(itemRepo.findbyId(id));
    
        item.ifPresentOrElse(()->System.out.println(item.get()), this::logNoItem());
    
    }
    
  3. # 3 楼答案

    我认为这里不需要Optional,一个简单的else就行了

    for (Id id : ids) {
        Item item = itemRepo.findbyId(id);
    
        if(item == null) {
            Log.error("No item by id");
        } else {
            // bla bla bla
        }
    }
    
  4. # 4 楼答案

    我也不太喜欢选修课。但如果您想使用它,这可能会起作用:

    List<Id> ids = new ArrayList<Id>();
    for (Id id : ids) {
        Optional.ofNullable(itemRepo.findbyId(id))
            .ifPresentOrElse(i -> process(i),
                () -> Log.error("No item by id"));
    }
    

    在我看来,Optionals应该与streams一起使用。for循环是流的最佳候选

    ids.stream()
        .map(itemRepo::findbyId)
        .map(Optional::ofNullable)
        .forEach(o -> o.ifPresentOrElse(i -> process(i), 
                () -> Log.error("No item by id")));