Java – Is Ruby #map or #collect equivalent to Java?

Is Ruby #map or #collect equivalent to Java?… here is a solution to the problem.

Is Ruby #map or #collect equivalent to Java?

Let’s say I have an array movies = get_movies().

I do this a lot in Ruby
movies.map {| movie| movie.poster_image_url } or similar.

What can I do like in Java? And equally elegant, concise and readable. I know there are countless ways to do this, but if there’s a good way to make me not want to use Groovy or something, let me know. I’m sure Java has some great ways to do things like this.

So far, this is what I use from https://github.com/holgerbrandl/themoviedbapi/ Java code for the TheMovieDB API Java wrapper

        TmdbMovies movies = new TmdbApi(BuildConfig.MOVIEDB_API_KEY).getMovies();
        MovieResultsPage results = movies.getPopularMovieList("en", 1);
         The following line is RubyJava and needs to your help!
        results.getResults().map {|e| e.getPosterPath() };
         or ... more RubyJava results.getResults().map(&:getPosterPath()); 

If you know a lot about Java but aren’t familiar with ruby, learn more about #map/#collect in Ruby. http://ruby-doc.org/core-1.9.3/Array.html#method-i-collect

So far, the closest I’ve seen with a few quick glances to answering this question… https://planet.jboss.org/post/java_developers_should_learn_ruby

These also look close. http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

So many options: Functional Programming in Java

This is also the Android … Is there anything good for Android developers to use out of the box and make this programming easy? It’s a functional programming style, right?

After receiving really good insights like “there’s nothing wrong with the for loop” and (basically) “syntax isn’t everything”, I decided not to try to make all of my Java look like Ruby! https://github.com/google/guava/wiki/FunctionalExplained .

Solution

There is a map method on the stream that accepts a method parameter.

collection.stream()
  .map(obj -> obj.someMethod())
  .collect(Collectors.toList()));

map returns another stream, so to retrieve the list of the collect method you called.

Too much to explain in the post, but you can visit this link, which helps me a lot :

http://winterbe.com/posts/2014/03/16/java-8-tutorial/

Related Problems and Solutions