溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java如何使用Pair實現成對結果的返回

發布時間:2022-03-11 11:43:20 來源:億速云 閱讀:535 作者:小新 欄目:編程語言

這篇文章主要介紹java如何使用Pair實現成對結果的返回,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

使用Pair實現成對結果的返回

在C/C++語言中,Pair(對)是將兩個數據類型組成一個數據類型的容器,比如std::pair。

Pair主要有兩種用途:

  1. 把key和value放在一起成對處理,主要用于Map中返回名值對,比如Map中的Entry類;

  2. 當一個函數需要返回兩個結果時,可以使用Pair來避免定義過多的數據模型類。

第一種用途比較常見,這里主要說明第二種用途。

1.定義模型類實現成對結果的返回

函數實現代碼:

/** 點和距離類 */@Setter@Getter@ToString@AllArgsConstructorpublic static class PointAndDistance {    /** 點 */
    private Point point;    /** 距離 */
    private Double distance;
}/** 獲取最近點和距離 */public static PointAndDistance getNearestPointAndDistance(Point point, Point[] points) {    // 檢查點數組為空
    if (ArrayUtils.isEmpty(points)) {        return null;
    }    // 獲取最近點和距離
    Point nearestPoint = points[0];    double nearestDistance = getDistance(point, points[0]);    for (int i = 1; i < points.length; i++) {        double distance = getDistance(point, point[i]);        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestPoint = point[i];
        }
    }    // 返回最近點和距離
    return new PointAndDistance(nearestPoint, nearestDistance);
}

函數使用案例:

Point point = ...;
Point[] points = ...;
PointAndDistance pointAndDistance = getNearestPointAndDistance(point, points);if (Objects.nonNull(pointAndDistance)) {
    Point point = pointAndDistance.getPoint();
    Double distance = pointAndDistance.getDistance();
    ...
}

2.使用Pair類實現成對結果的返回

在JDK中,沒有提供原生的Pair數據結構,也可以使用Map::Entry代替。不過,Apache的commons-lang3包中的Pair類更為好用,下面便以Pair類進行舉例說明。

函數實現代碼:

/** 獲取最近點和距離 */public static Pair<Point, Double> getNearestPointAndDistance(Point point, Point[] points) {    // 檢查點數組為空
    if (ArrayUtils.isEmpty(points)) {        return null;
    }    // 獲取最近點和距離
    Point nearestPoint = points[0];    double nearestDistance = getDistance(point, points[0]);    for (int i = 1; i < points.length; i++) {        double distance = getDistance(point, point[i]);        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestPoint = point[i];
        }
    }    // 返回最近點和距離
    return Pair.of(nearestPoint, nearestDistance);
}

函數使用案例:

Point point = ...;
Point[] points = ...;
Pair<Point, Double> pair = getNearestPointAndDistance(point, points);if (Objects.nonNull(pair)) {
    Point point = pair.getLeft();
    Double distance = pair.getRight();
    ...
}

以上是“java如何使用Pair實現成對結果的返回”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女