In C/C language, Pair (pair) is a container that combines two data types into one data type, such as std::pair.
Pair has two main uses:
Put key and value together for pair processing, mainly used to return name-value pairs in Map, such as in Map Entry class;
When a function needs to return two results, you can use Pair to avoid defining too many data model classes.
The first use is more common, here we mainly explain the second use.
Function implementation code:
/** 点和距离类 */@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); }
Function usage case:
Point point = ...; Point[] points = ...; PointAndDistance pointAndDistance = getNearestPointAndDistance(point, points);if (Objects.nonNull(pointAndDistance)) { Point point = pointAndDistance.getPoint(); Double distance = pointAndDistance.getDistance(); ... }
In the JDK, the native Pair data structure is not provided, and Map::Entry can be used instead. However, the Pair class in Apache's commons-lang3 package is easier to use. The following uses the Pair class as an example.
Function implementation code:
/** 获取最近点和距离 */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); }
Function use case:
Point point = ...; Point[] points = ...; Pair<Point, Double> pair = getNearestPointAndDistance(point, points);if (Objects.nonNull(pair)) { Point point = pair.getLeft(); Double distance = pair.getRight(); ... }
The above is the detailed content of How to use Pair in java to return paired results. For more information, please follow other related articles on the PHP Chinese website!