javaandroidflatmapgpx

Getting all wayPoints from a GPX object by stream and map


I'm attempting to use com.github.ticofab:android-gpx-parser:2.2.0 in my project.

Migrating from 'io.jenetics:jpx:2.2.0'. I actually got it working in android. But later(after putting it in production) found that some GPX files will try requesting an unavailable dependency, crashing the app.

This snippet of code I was using with JPX. But I'm having a hard time switching it over android-gpx-parser.

import com.google.android.gms.maps.model.LatLng;

public ArrayList<LatLng> getWaypointLatLngs (GPX gpx) {
        ArrayList<LatLng> latLngPoints = new ArrayList<>();
        gpx.tracks()
            .flatMap(Track::segments)
            .flatMap(TrackSegment::points)
            .forEach(w -> latLngPoints.add(
                 new LatLng( w.getLatitude().doubleValue(), w.getLongitude().doubleValue())));
        return latLngPoints;
    }

Here's what I'm trying to do with android-gpx-parser.

public ArrayList<LatLng> getWaypointLatLngs (Gpx gpx) {
    ArrayList<LatLng> latLngPoints = new ArrayList<>();
    gpx.getTracks().stream().flatMap(Track::getTrackSegments)
            .flatMap(TrackSegment::getTrackPoints)
            .forEach(w -> latLngPoints.add(
                new LatLng( w.getLatitude().doubleValue(), w.getLongitude().doubleValue())));
    return latLngPoints;
}

The IDE is tell me I'm declaring a method reference and it is expecting a Function (with map or flatMap).

enter image description here

Is there an elegant way of getting all waypoints (points) with from a Gpx object using android-gpx-parser?


Solution

  • Figured it out. Here's my solution.

    public ArrayList<LatLng> getWaypointLatLngs (Gpx gpx) {
    
        ArrayList<LatLng> latLngPoints = new ArrayList<>();
    
         gpx.getTracks().stream().flatMap(track -> track.getTrackSegments().stream())
                .flatMap(trackPoints -> trackPoints.getTrackPoints().stream())
                .forEach(w -> latLngPoints.add(new LatLng(w.getLatitude(), w.getLongitude())));
    
        return latLngPoints;
    }