samba
samba

Reputation: 3111

Java 8 - how to process arrays of non-primitive types?

I'm using Google maps API and want to process search results. The result is returned as an Array of non-primitive types PlacesSearchResult[].

I want to build an array of locations, LatLng[] represented by a latitude/longitude pairs using data from the places search results array.

Here is how I did it with Java 7:

PlacesSearchResult[] searchResults = placesSearchResponse.results;
int placesCount = searchResults.length;

    LatLng[] locations = new LatLng[placesCount];
    for (int i = 0; i < placesCount; i++) {
        locations[i] = searchResults[i].geometry.location;
    }

I decided to try using Java 8 here but got confused with how to process the arrays of non-primitives. If it was an array of primitive types I would do something like this:

int[] a = ...
int[] result = IntStream.range(0, a.length)
.map(i -> a[i])
.toArray();

What would be the correct way to process the arrays of objects?

Upvotes: 2

Views: 472

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56489

You can create a stream from the searchResults, map it to LatLng's and then collect to an array as follows:

Arrays.stream(searchResults)
      .map(s -> s.geometry.location)  
      .toArray(LatLng[]::new);  

As for your current solution, the problem with it is that instead of using IntStream.map you should use mapToObj as you're trasforming to object types and not primitive types then finish it off with specifying the type of the array elements in the toArray method. example:

IntStream.range(0, searchResults.length)
         .mapToObj(i -> a[i].geometry.location)
         .toArray(LatLng[]::new);

Upvotes: 3

Related Questions