Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an entity that has a position value in the list. And you need to determine the value of the next position, by obtaining the last value and increasing by one. If there is no one element, then return zero.

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;
    }
}

Is it possible to somehow make changes in a single line so that for the obtained maximum value immediately increase by one if there is and if not, then return zero

That is, such as such (pseudocode):

long value = entities.stream()
                .mapToLong(Entity::getPositionInList)
                .max()
                .map(i -> i + 1)    // it's not work, just what i want
                .orElse(0L);
like image 745
FreeOnGoo Avatar asked May 13 '19 13:05

FreeOnGoo


2 Answers

Just return -1 if nothing is found, then your normal value will be incremented by 1 if it is present and else it will result in 0 if nothing is found.

long value = entities.stream()
                     .mapToLong(Entity::getPositionInList)
                     .max()
                     .orElse(-1) + 1;
like image 200
Lino Avatar answered Oct 14 '22 08:10

Lino


you could map instead of mapToLong:

 entities.stream()
         .map(Entity::getPositionInList)
         .max(Comparator.naturalOrder())    
         .map(i -> i + 1)            
         .orElse(0L);
like image 26
Eugene Avatar answered Oct 14 '22 08:10

Eugene