'Error converting Optional<String> to Integer from TextInputDialog

In this example I have tempSocket1 and tempSocket2 but I really just want one of them. I just included both to show I tried both methods, but I keep getting an error, "the method valueOf(String) in the type Integer is not applicable for the arguments (Optional)." I thought both of these methods were the ones used for converting a string data type to integer, but I'm not sure how the Optional part changes the whole system.

private void showTextInputDialog() {
        TextInputDialog changePort = new TextInputDialog("Settings");
        changePort.setHeaderText("Change Port");
        changePort.setContentText("Please enter port number to be used for establishing connection...");

        Optional<String> result = changePort.showAndWait();
        result.ifPresent(e -> {
            Integer tempSocket1 = Integer.valueOf(result);
            Integer tempSocket2 = Integer.parseInt(result);
            }
        );
}


Solution 1:[1]

You see, Integer.valueOf and Integer.parseInt methods need an argument of type String, but you are passing an Optional<String>. So that's why the error occurred. Optional string and string are not the same.

Just think about this, if Optional<String> were the same as String, would ArrayList<String> be the same as String? Would LinkedList<String> be the same as String? What about HashMap<String, Integer>? Would it be both a String and an Integer?

The chaos that treating generic types the same as their generic type arguments would bring is destructive! Imagine calling charAt on an optional string! Without the implementation, no one knows what will happen...

So yeah, never think that generic types are the same types as the generic type parameters.

Solution 2:[2]

To convert an Optional to an Integer, it is necessary to invoke the get() method before the conversion.

Optional<String> cadena = Optional.of("333");
Integer num = Integer.valueOf(cadena.get());

Solution 3:[3]

Just to extend other answers it may looks better using map method, and even more with lambda and method reference:

Optional<String> result = changePort.showAndWait();
Integer tempSocket = result.map(Integer::valueOf).orElse(8080);

Solution 4:[4]

You're trying to pass an Optional<String> instead of a normal String. You need to fetch the string first with .get() before converting your result to an integer. Or use result.ifPresent(e ...) that will automatically unwrap the optional value and convert it to an Integer.

Optional<String> result = changePort.showAndWait();
result.ifPresent(e -> {
    Integer tempSocket1 = Integer.valueOf(e);
    Integer tempSocket2 = Integer.parseInt(e);
    }
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sweeper
Solution 2 davidddp
Solution 3 iMysak
Solution 4 mnish