首页 > Java > java教程 > 正文

使用 Java 8 Stream API 将 List 转换为 TreeMap

碧海醫心
发布: 2025-07-28 16:04:11
原创
518人浏览过

使用 java 8 stream api 将 list 转换为 treemap

本文介绍了如何使用 Java 8 Stream API 将一个 List<Point3d> 转换为 TreeMap<Double, Point3d>,并找到距离给定点最近的点。 通过 Collectors.toMap 方法,我们可以直接将流收集到 TreeMap 中,避免了中间步骤。同时,文章也讨论了使用 forEach 方法的替代方案,并分析了两种方法的可读性和性能。

使用 Stream API 转换为 TreeMap

Java 8 Stream API 提供了强大的数据处理能力。 将 List 转换为 TreeMap 的常见场景是需要对数据进行排序,并且键值唯一。 以下是如何使用 Stream API 完成这个任务的示例:

假设我们有一个 List<Point3d>,我们想要创建一个 TreeMap<Double, Point3d>,其中键是 Point3d 对象到某个参考点 parentStartVertex 的距离,值是 Point3d 对象本身。

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<Point3d> points, Point3d parentStartVertex) {
        TreeMap<Double, Point3d> 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<Point3d> 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免费学习笔记(深入)”;

  1. points.stream(): 将 List<Point3d> 转换为一个 Stream。
  2. 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 中。
  3. distanceMap.firstEntry().getValue(): 获取 TreeMap 中第一个条目的值,即距离 parentStartVertex 最近的 Point3d 对象。

使用 forEach 循环转换为 TreeMap

虽然 Stream API 提供了简洁的解决方案,但使用传统的 forEach 循环也可以实现相同的功能,有时甚至更具可读性:

Swapface人脸交换
Swapface人脸交换

一款创建逼真人脸交换的AI换脸工具

Swapface人脸交换 45
查看详情 Swapface人脸交换
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<Point3d> points, Point3d parentStartVertex) {
        TreeMap<Double, Point3d> distanceMap = new TreeMap<>();
        points.forEach(point -> distanceMap.put(parentStartVertex.distanceTo(point), point));
        return distanceMap.firstEntry().getValue();
    }

    public static void main(String[] args) {
        List<Point3d> 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免费学习笔记(深入)”;

  1. TreeMap<Double, Point3d> distanceMap = new TreeMap<>();: 创建一个新的 TreeMap 实例。
  2. 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<Point3d> 转换为 TreeMap<Double, Point3d>,并找到距离给定点最近的点。 Stream API 提供了简洁的声明式编程风格,而 forEach 循环则更简单直接。 选择哪种方法取决于个人偏好和具体场景。 在实际应用中,应该根据具体业务逻辑选择合适的键冲突处理策略,并进行空值检查,以避免潜在的异常。

以上就是使用 Java 8 Stream API 将 List 转换为 TreeMap的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号