如何调用可选对象的Get()方法

问题描述 投票:-1回答:2

我的任务是实现可用于表示点和轨道的类,以及演示类的使用的小程序。

在Track类中,我实现了一个从CSV文件读取数据的方法,解析它并将数据添加到ArrayList:List<Point> track = new ArrayList<> ();

这是readFile()方法:

// readFile method that creates a sequence of point objects from data in a file, the name of which is supplied as a string parameter
    public void readFile(String test) throws FileNotFoundException {

        // Scanner for specified file
        Scanner input = new Scanner(new File(test));
        int iteration = 0;
        track.clear ();

        //Fetch and parse
        while (input.hasNextLine ())  {
            String newLine = input.nextLine ();
            if (iteration == 0) { iteration++; continue;}
                String delimiter = ",";
                String[] line = newLine.split(delimiter);
            if (line.length != 4) {
                throw new GPSException ("File contains illegal number of values.");
            }
            else {
                ZonedDateTime time  = ZonedDateTime.parse (line[0]);
                double longitude = Double.parseDouble (line[1]);
                double latitude  = Double.parseDouble (line[2]);
                double elevation = Double.parseDouble (line[3]);

                Point newPoint = new Point (time, longitude, latitude, elevation);
                track.add (newPoint);
            }
        }
            input.close ();
        }

除了各种方法,如add(),size()和get()(都是自解释),我还实现了两种方法来找到最低点和最高点。为此,我使用Streams API - 但问题是方法必须返回Point对象,而不是Optionals。我知道Optional对象有一个get()方法返回包含的对象,所以使用它会修复观察到的问题,但我不知道如何用我已经为函数编写的代码调用这个方法:

// Lowest point method
    public Optional<Point> lowestPoint() {
        return track.stream().min (Comparator.comparingDouble (Point::getElevation));
    }

    // Highest point method
    public Optional<Point> highestPoint() {
        return track.stream().max (Comparator.comparingDouble (Point::getElevation));
    }

我还想为这两个方法添加验证,但是会欣赏有关如何正确调用get()方法的任何指导,以便我可以返回Point对象而不是Optional对象。

我已经将验证添加到方法中,并且它通过了提供的单元测试(我的讲师提供了一组带有赋值的测试)。但伙计们,我会承认。

在整个程序的大部分时间内使用的验证是我们为我们创建的验证,其定义如下:

public class GPSException extends RuntimeException {
  public GPSException(String message) {
    super(message);
  }

问题是,当使用.get()或.else()返回一个点对象时,我仍然遇到各种各样的问题。我在类中创建了一个新的Point实例,但实例被拒绝了。代码如下:

// Lowest point method
    public Optional<Point> lowestPoint() {
        ZonedDateTime time = ZonedDateTime.now ();
        double longitude = 0;
        double latitude = 0;
        double elevation = 0;
        if (track.size () != 4) {
            throw new GPSException ("Not enough points to compute");
        } else {
            Point lp = new Point (time, longitude, latitude, elevation);
            return track.stream ()
                        .min (Comparator.comparingDouble (Point::getElevation))
                        .orElse (lp);
        }
    }

我正在努力弄清楚我做错了什么。

java arraylist java-stream optional
2个回答
0
投票

您可以使用Optional::orElse返回默认值:

public Point lowestPoint() {
    return track.stream()
                .min(Comparator.comparingDouble(Point::getElevation))
                .orElse(someDefaultValue);
}

同样对于highestPoint

public Point highestPoint() {
    return track.stream()
                .max(Comparator.comparingDouble(Point::getElevation))
                .orElse(someDefaultValue);
}

0
投票

Optional API具有多种方法,可根据可选项包含的内容处理所需结果,包括:

  • (如GBlodgett所述)orElse方法,如果可选项为空,则返回备用(通常为“默认”)值,或者
  • 有趣的是在这里 - 如果你想要抛出一个例外,如果orElseThrow是空的,Supplier<Throwable>采取Optional
  • 等等等等

最简单(但不可取)的方式当然是将get链接到你的minmax调用,这将返回Point实例,或者如果NoSuchElementException为空则抛出Optional

建议的做法是利用Optional API来处理minmax调用没有返回值的情况。

© www.soinside.com 2019 - 2024. All rights reserved.