Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return a Direction instance by input degrees or empty Optional if there is none

guys. I have an enum class with directions and degree values in them. With "ofDegrees" method, I have to return a Direction object with the name of field (for example: SW) if input degrees match with direction degrees, and if there’s no match to return empty Optional.

I tried with converting the degrees input to object and then check for equality between the input and enum values.

public enum Direction {
N(0), NE(45), E(90), SE(135), S(180), SW(225), W(270), NW(315);

Direction(final int degrees) {
    this.degrees = degrees;
}

private int degrees;

public static Direction ofDegrees(int degrees) {
    Optional<Integer> opt = Optional.ofNullable(degrees);
    Direction direction = null;
    if(opt.isPresent()) {
        Object obj = Integer.valueOf(degrees);
        for(Direction dir : Direction.values()) {
            if(dir == obj) {
                direction = dir;
            }
        }
    }
    return direction;        
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In every case i get "null" for result. And the other thing that i cant understand is how can i return empty optional when i cant convert from Optional to Direction?

Thanks in andvance.

>Solution :

you’re mixing non optional input argument and optional return, then you’re compaing Direction object with optional – they will never be equal, probably you need something like this:

public static Optional<Direction> ofDegrees(int degrees) {
    for (Direction dir : Direction.values()) {
        if (dir.degrees == degrees) {
            return Optional.of(dir);
        }
    }
    return Optional.empty();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading