本文介绍了如何使用 Java 8 Stream API 将一个 List
Java 8 Stream API 提供了强大的数据处理能力。 将 List 转换为 TreeMap 的常见场景是需要对数据进行排序,并且键值唯一。 以下是如何使用 Stream API 完成这个任务的示例:
假设我们有一个 List
import java.util.List;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
class Point3d {
private double x;
private double y;
private double z;
public Point3d(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.x - other.x, 2) +
Math.pow(this.y - other.y, 2) +
Math.pow(this.z - other.z, 2));
}
@Override
public String toString() {
return "Point3d{" +
"x=" + x +
", y=" + y +
", z=" + z +
'}';
}
}
public class StreamTreeMapConverter {
public Point3d findClosestNodeToParentStartNode(List points, Point3d parentStartVertex) {
TreeMap distanceMap = points.stream().collect(
Collectors.toMap(
parentStartVertex::distanceTo, // Key mapper: 计算距离
Function.identity(), // Value mapper: 使用 Point3d 本身作为值
(k1, k2) -> k2, // Merge function: 如果键冲突,选择后一个值 (k2)
TreeMap::new // Supplier: 使用 TreeMap 作为目标 Map
));
return distanceMap.firstEntry().getValue();
}
public static void main(String[] args) {
List points = List.of(
new Point3d(1, 2, 3),
new Point3d(4, 5, 6),
new Point3d(7, 8, 9)
);
Point3d parentStartVertex = new Point3d(0, 0, 0);
StreamTreeMapConverter converter = new StreamTreeMapConverter();
Point
3d closestPoint = converter.findClosestNodeToParentStartNode(points, parentStartVertex);
System.out.println("Closest point: " + closestPoint);
}
} 代码解释:
虽然 Stream API 提供了简洁的解决方案,但使用传统的 forEach 循环也可以实现相同的功能,有时甚至更具可读性:
import java.util.List;
import java.util.TreeMap;
class Point3d {
private double x;
private double y;
private double z;
public Point3d(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.x - other.x, 2) +
Math.pow(this.y - other.y, 2) +
Math.pow(this.z - other.z, 2));
}
@Override
public String toString() {
return "Point3d{" +
"x=" + x +
", y=" + y +
", z=" + z +
'}';
}
}
public class ForEachTreeMapConverter {
public Point3d findClosestNodeToParentStartNode(List points, Point3d parentStartVertex) {
TreeMap distanceMap = new TreeMap<>();
points.forEach(point -> distanceMap.put(parentStartVertex.distanceTo(point), point));
return distanceMap.firstEntry().getValue();
}
public static void main(String[] args) {
List points = List.of(
new Point3d(1, 2, 3),
new Point3d(4, 5, 6),
new Point3d(7, 8, 9)
);
Point3d parentStartVertex = new Point3d(0, 0, 0);
ForEachTreeMapConverter converter = new ForEachTreeMapConverter();
Point3d closestPoint = converter.findClosestNodeToParentStartNode(points, parentStartVertex);
System.out.println("Closest point: " + closestPoint);
}
} 代码解释:
两种方法在功能上是等价的,但它们在性能和可读性方面可能有所不同。
在大多数情况下,两种方法的性能差异可以忽略不计。 选择哪种方法取决于个人偏好和具体场景。 如果代码的可读性和简洁性更重要,那么 Stream API 可能是更好的选择。 如果性能是关键因素,并且可以接受更冗长的代码,那么 forEach 循环可能更合适。
本文介绍了如何使用 Java 8 Stream API 和 forEach 循环将 List