List#Stream() Example

package tech.otter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
	    List<Article> articles = new ArrayList<>();
        articles.add( new Article("7 ways to skin a cat", "NewzFeed", Arrays.asList("anatomy", "click bait", "cat")));
        articles.add( new Article("You won't believe how...", "NewzFeed", Arrays.asList("gossip", "click bait")));
        articles.add( new Article("My Trip to Japan", "BlogWorld", Arrays.asList("blog", "travel", "Japan")));
        articles.add( new Article("A Cat named Simon", "BlogWorld", Arrays.asList("blog", "reflection", "cat")));

        articles.stream()
                .filter(p -> p.tags.contains("cat"))
                .forEach(System.out::println);
                // equivalent to .forEach(p -> System.out.println(p))
    }

    private static class Article {
        String name;
        String publisher;
        List<String> tags = new ArrayList<>();

        Article(String name, String publisher, List<String> tags) {
            this.name = name;
            this.publisher = publisher;
            this.tags = tags;
        }

        @Override
        public String toString() {
            return String.format("name: '%s', publisher: '%s'", name, publisher);
        }
    }
}
List#Stream Example

The result is:

name: ‘7 ways to skin a cat’, publisher: ‘NewzFeed’
name: ‘A Cat named Simon’, publisher: ‘BlogWorld’

Note how line 18 is the non-lambda version of 19.