
本文介绍了如何使用 Java 8 Stream API 将一个 List
使用 Stream API 转换为 TreeMap
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();
Point3d closestPoint = converter.findClosestNodeToParentStartNode(points, parentStartVertex);
System.out.println("Closest point: " + closestPoint);
}
} 代码解释:
立即学习“Java免费学习笔记(深入)”;
-
points.stream(): 将 List
转换为一个 Stream。 -
Collectors.toMap(...): 使用 Collectors.toMap 方法将 Stream 收集到一个 Map 中。
- parentStartVertex::distanceTo: 这是一个方法引用,它将 parentStartVertex 对象的 distanceTo 方法作为键的生成函数。 对于流中的每个 Point3d 对象,它计算到 parentStartVertex 的距离,并将该距离作为键。
- Function.identity(): 这是一个函数,它返回输入对象本身。 在这里,它表示将 Point3d 对象本身作为值。
- (k1, k2) -> k2: 这是一个合并函数,用于处理键冲突的情况。 如果两个 Point3d 对象到 parentStartVertex 的距离相同(即键相同),则此函数决定保留哪个值。 在这里,我们简单地选择后一个值 k2。 在实际应用中,你可能需要根据具体业务逻辑选择合适的合并策略。
- TreeMap::new: 这是一个构造函数引用,它指定使用 TreeMap 作为目标 Map 的类型。 Collectors.toMap 方法将使用此构造函数创建一个新的 TreeMap,并将流中的数据收集到该 Map 中。
- distanceMap.firstEntry().getValue(): 获取 TreeMap 中第一个条目的值,即距离 parentStartVertex 最近的 Point3d 对象。
使用 forEach 循环转换为 TreeMap
虽然 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);
}
} 代码解释:
立即学习“Java免费学习笔记(深入)”;
-
TreeMap
distanceMap = new TreeMap(); : 创建一个新的 TreeMap 实例。 - points.forEach(point -> distanceMap.put(parentStartVertex.distanceTo(point), point));: 使用 forEach 循环遍历 points 列表,并将每个 Point3d 对象及其到 parentStartVertex 的距离添加到 distanceMap 中。
性能和可读性
两种方法在功能上是等价的,但它们在性能和可读性方面可能有所不同。
- Stream API: Stream API 的优势在于其声明式编程风格,代码更简洁,更易于理解其意图。 此外,Stream API 允许并行处理,可以在多核 CPU 上提高性能。 但是,Stream API 也有一定的开销,例如创建 Stream 对象和执行中间操作。
- forEach 循环: forEach 循环的优势在于其简单性和直接性。 它没有 Stream API 的额外开销,因此在某些情况下可能更快。 但是,forEach 循环是命令式编程风格,代码可能更冗长,更难理解其意图。
在大多数情况下,两种方法的性能差异可以忽略不计。 选择哪种方法取决于个人偏好和具体场景。 如果代码的可读性和简洁性更重要,那么 Stream API 可能是更好的选择。 如果性能是关键因素,并且可以接受更冗长的代码,那么 forEach 循环可能更合适。
注意事项
- 键的唯一性: TreeMap 要求键是唯一的。 如果 List 中存在多个 Point3d 对象到 parentStartVertex 的距离相同,那么只有最后一个对象会被添加到 TreeMap 中。 如果需要处理键冲突的情况,可以使用 Collectors.toMap 方法的合并函数来指定如何处理冲突。
- 空指针异常: 如果 points 列表为 null,或者 parentStartVertex 为 null,则可能会抛出空指针异常。 在使用这些方法之前,应该先进行空值检查。
- 数据类型: 确保键的数据类型实现了 Comparable 接口,以便 TreeMap 可以正确地对键进行排序。 在上面的示例中,我们使用 Double 作为键的数据类型,它实现了 Comparable 接口。
总结
本文介绍了如何使用 Java 8 Stream API 和 forEach 循环将 List










