Java 如何使用可选值为int变量赋值?

Java 如何使用可选值为int变量赋值?,java,java-8,optional,Java,Java 8,Optional,例如,我得到了如下代码: class Point { private String x; private String y; public String getX () { //Here can not use Optional<String> return this.x; } public String getY () { return this.y; } public Point(Str

例如,我得到了如下代码:

class Point
{
    private String x;
    private String y;

    public String getX () { //Here can not use Optional<String>
        return this.x;
    }

    public String getY () {
        return this.y;
    }

    public Point(String x, String y) {
        this.x = x;
        this.y = y;
    }
}
this.x = ofNullable(point.getX()).ifPresent((x) -> x)
我想用一种更干净的方式,像这样:

class Point
{
    private String x;
    private String y;

    public String getX () { //Here can not use Optional<String>
        return this.x;
    }

    public String getY () {
        return this.y;
    }

    public Point(String x, String y) {
        this.x = x;
        this.y = y;
    }
}
this.x = ofNullable(point.getX()).ifPresent((x) -> x)

我知道这不起作用,但我几乎尝试了所有方法,但都无法使其起作用。

您必须使用
Integer
而不是原始类型
int

您没有发布足够的代码,但是您的
getX
方法定义应该是:

可选的getX()
而不是
int getX()

如果无法使用该方法修改该类,请创建一个包装类或其他内容。没有看到所有的代码,我不能说更多

编辑:

使您的point类存储可选值:

class Point
{
    private Optional<String> x;
    private Optional<String> y;

    public Optional<String> getX () { //Here can not use Optional<String>
        return this.x;
    }

    public Optional<String> getY () {
        return this.y;
    }

    public Point(String x, String y) {
        this.x = ofNullable(x);
        this.y = ofNullable(y);
    }
}

of nullable(point.getY().isPresent()
有点混乱。
getY()
是否返回一个可选值?或者您是否在
point
上创建了一个可选值?这里的括号不正确。@ernest_k我编辑了代码。有这些条件吗?您可以使用
of nullable(point.getX())。如果存在(x->this.x=x)
但这并不比惯用的
更简洁,如果(point.getX()!=null)this.x=point.getX();
我扩展了代码,我希望现在清楚我想要什么。我在那里发表了评论,我不想让它们成为可选的。