簡體   English   中英

執行.max()方法時如何在java流中增加值

[英]How in the java stream when executing the .max() method do increment value

我有一個在列表中有位置值的實體。 並且您需要通過獲取最后一個值並增加1來確定下一個位置的值。 如果沒有一個元素,則返回零。

public class App {
    public static void main(String[] args) {
        ArrayList<Entity> entities = new ArrayList<>();

        long nextPositionOrFirstIfNotExistWhenEmpty = getNextPositionOrFirstIfNotExist(entities);
        if (nextPositionOrFirstIfNotExistWhenEmpty != 0L) {
            throw new RuntimeException("Invalid");
        }

        entities.add(new Entity(2L));
        entities.add(new Entity(123L));
        entities.add(new Entity(3L));

        long nextPositionOrFirstIfNotExist = getNextPositionOrFirstIfNotExist(entities);
        if (nextPositionOrFirstIfNotExist != 124L) {
            throw new RuntimeException("Invalid");
        }
    }

    // how to refactoring this? not like "optionalLong.isPresent()"
    public static long getNextPositionOrFirstIfNotExist(List<Entity> entities) {
        OptionalLong optionalLong = entities.stream()
                .mapToLong(Entity::getPositionInList)
                .max();

        return optionalLong.isPresent() ? optionalLong.getAsLong() + 1 : 0L;
    }
}

class Entity {

    public Entity(Long positionInList) {
        this.positionInList = positionInList;
    }

    private Long positionInList;

    public Long getPositionInList() {
        return positionInList;
    }

    public void setPositionInList(Long positionInList) {
        this.positionInList = positionInList;
    }
}

是否有可能以某種方式在一行中進行更改,以便對於獲得的最大值,如果有,則立即增加1,然后返回零

就是這樣的(偽代碼):

long value = entities.stream()
                .mapToLong(Entity::getPositionInList)
                .max()
                .map(i -> i + 1)    // it's not work, just what i want
                .orElse(0L);

如果沒有找到,只返回-1如果存在,則正常值將增加1 ,否則如果沒有找到則將導致0

long value = entities.stream()
                     .mapToLong(Entity::getPositionInList)
                     .max()
                     .orElse(-1) + 1;

你可以map而不是mapToLong

 entities.stream()
         .map(Entity::getPositionInList)
         .max(Comparator.naturalOrder())    
         .map(i -> i + 1)            
         .orElse(0L);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM