Search code examples
javalambdajava-8java-streamcollectors

Java 8 stream API to convert List to TreeMap


Hi i am trying to convert the following code using java 8 stream API.

private Point3d findClosestNodeToParentStartNode1(List<Point3d> points,Point3d parentStartVertex)
    {
        
        TreeMap<Double, Point3d> distanceMap = new TreeMap<Double, Point3d>();
        for (Point3d point : points) {
            distanceMap.put(parentStartVertex.distanceTo(point), point);
        }
        return distanceMap.firstEntry().getValue();
    }

I am trying to do something like

Map<Double, Point3d> result =  points.stream().collect(Collectors.toMap(parentStartVertex.distanceTo(point->point) , point -> point));
TreeMap<Double, Point3d> distanceMap = new TreeMap<>(result);
return distanceMap.firstEntry().getValue();

Solution

  • Your code won't even compile as the key function is wrong. You also have an intermediate step which isn't needed, you can directly use the toMap function which takes 4 arguments and return a TreeMap directly.

    Something like this should work

    TreeMap <Double, Point3d> distanceMap = points.stream().collect(
    Collectors.toMap(
      parentStartVertex::distanceTo,
      Function.identity(),
      (k1, k2) -> k2,
      TreeMap::new));
    return distanceMap.firstEntry().getValue();
    

    For what is worth I don't think there is anything wrong with the forEach approach and in this case it might even be easier to read (and might even be faster due to less overhead).

    TreeMap<Double, Point3d> distanceMap = new TreeMap<Double, Point3d>();
    points.forEach( point -> distanceMap.put(parentStartVertex.distanceTo(point), point));
    return distanceMap.firstEntry().getValue();