javaandroidretrolambda

How would you iterate through a list in retrolambda?


I have the following code

List<Trailer> trailers = response.body().getResults();
trailers.stream().forEach(trailer -> {
    View reviewView = LayoutInflater.from(mContext).inflate(R.layout.trailer_list_item, null);
    ((TextView) reviewView.findViewById(R.id.movies_trailers_list)).setText(trailer.getName());
    LinearLayout linearLayout = (LinearLayout) mView.findViewById(R.id.movie_trailers);
    linearLayout.addView(reviewView);
});

Is there a way to get this same code to work with retrolambda? I need to iterate throught list results I get back and add it a view.

Any advice would be greatly appreciated.


Solution

  • I'd kindly suggest to use streamsupport as an additional library for the Java 8 streams part:

    import java8.util.stream.StreamSupport;
    
    StreamSupport.stream(trailers).forEach(trailer -> {
        View reviewView = LayoutInflater.from(mContext).inflate(R.layout.trailer_list_item, null);
        ((TextView) reviewView.findViewById(R.id.movies_trailers_list)).setText(trailer.getName());
        LinearLayout linearLayout = (LinearLayout) mView.findViewById(R.id.movie_trailers);
        linearLayout.addView(reviewView);
    });
    

    The required changes for Java 8 stream code are usually quite small and (in most cases) mechanic.

    It has extra appeal in that it also already provides the new Java 9 Stream methods takeWhile / dropWhile and all other Java 9 enhancements (especially in Optional and Collectors) and optimizations. You can find the API doc here.