DEV Community

loading...

Using Java's Stream API

brittcodes profile image Britt Codes ・3 min read

An Interface introduced in Java 8, contributed to declarative programming in Java. Declarative programming is a style of programming that describes what you want, instead of telling the compiler how to do it, which is Imperative programming. A Stream is a sequence of elements supporting sequential and parallel aggregate operations. In other words, it allows us to define a pipeline of operations to process a sequence of elements.

The stream pipeline starts off with a source that can be an array, a collection, an I/O channel, etc. Attached to that source is anywhere from none to multiple intermediate operations, and finally a terminal operation, which produces a result. Streams are lazy and computation only takes place once the terminal operation is initiated.

Below I'll demonstrate some functionality that the Java Stream API offers.

The Object we'll be using to demonstrate functionality:

public class Pet {

    private final String name;
    private final int age;
    private final Type type;

    public Pet(String name, int age, Type type) {
        super();
        this.name = name;
        this.age = age;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Type getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Pet [name=" + name + ", age=" + age + "]";
}
    }
Enter fullscreen mode Exit fullscreen mode

Along with the Enum used to describe the type of Pet:

public enum Type {
    DOG, CAT
}
Enter fullscreen mode Exit fullscreen mode

Now onto the demonstration:

public class Demo {


    public static void main(String[] args) {
        List<Pet> petAnimals = getPets();

        // find all dogs
        System.out.println("Find All Dogs");
        List<Pet> dogs = petAnimals.stream()
                .filter(animal -> animal.getType().equals(Type.DOG))
                .collect(Collectors.toList());
        dogs.forEach(System.out::println);

        // sort by age
        System.out.println("\nSort By Age");
        List<Pet> ages = petAnimals.stream()
                .sorted(Comparator.comparing(Pet::getAge))
                .collect(Collectors.toList());
        ages.forEach(System.out::println);

        // average age of cats
        System.out.println("\nAverage Age of Cats");
        Double avgCatAge = petAnimals.stream()
                .filter(animal -> animal.getType().equals(Type.CAT))
                .collect(Collectors.averagingInt(Pet::getAge));
        System.out.println(avgCatAge);

        // average age of all pets
        System.out.println("\nAverage Age of Pets");
        Double avgPetAge = petAnimals.stream()
                .collect(Collectors.averagingInt(Pet::getAge));
        System.out.println(avgPetAge);

        // name of youngest dog
        System.out.println("\nName of Youngest Dog");
        petAnimals.stream()
            .filter(animal -> animal.getType().equals(Type.DOG))
            .min(Comparator.comparing(Pet::getAge))
            .map(animal -> animal.getName())
            .ifPresent(System.out::println);

        // number of cats
        System.out.println("\nNumber of Cats");
        long numOfCats = petAnimals.stream()
            .filter(animal -> animal.getType().equals(Type.CAT))
            .count();
        System.out.println(numOfCats);


    }

    private static List<Pet> getPets(){
        return Arrays.asList(
            new Pet("Marley", 5, Type.DOG),
            new Pet("Beethoven", 2, Type.CAT),
            new Pet("Ernest", 4, Type.DOG),
            new Pet("Tabby", 7, Type.CAT),
            new Pet("Snowball", 1, Type.CAT),
            new Pet("Lassie", 3, Type.DOG),
            new Pet("Little Nicky", 6, Type.CAT),
            new Pet("Copper", 12, Type.DOG)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode
// find all dogs
        System.out.println("Find All Dogs");
        List<Pet> dogs = petAnimals.stream()
                .filter(animal -> animal.getType().equals(Type.DOG))
                .collect(Collectors.toList());
        dogs.forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. Filter out the Objects based on Type into another stream
  3. returns only the objects matching the previous predicate
// sort by age
        System.out.println("\nSort By Age");
        List<Pet> ages = petAnimals.stream()
                .sorted(Comparator.comparing(Pet::getAge))
                .collect(Collectors.toList());
        ages.forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. Sort the stream of objects in ascending order based on age
  3. returns only the objects matching the previous predicate
// average age of cats
        System.out.println("\nAverage Age of Cats");
        Double avgCatAge = petAnimals.stream()
                .filter(animal -> animal.getType().equals(Type.CAT))
                .collect(Collectors.averagingInt(Pet::getAge));
        System.out.println(avgCatAge);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. Filter out the Objects based on Type into another stream
  3. reduce stream to the objects matching the mean of the given function
// average age of all pets
        System.out.println("\nAverage Age of Pets");
        Double avgPetAge = petAnimals.stream()
                .collect(Collectors.averagingInt(Pet::getAge));
        System.out.println(avgPetAge);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. reduce stream to the objects matching the mean of the given function
// name of youngest dog
        System.out.println("\nName of Youngest Dog");
        petAnimals.stream()
            .filter(animal -> animal.getType().equals(Type.DOG))
            .min(Comparator.comparing(Pet::getAge))
            .map(animal -> animal.getName())
            .ifPresent(System.out::println);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. Filter out the Objects based on Type into another stream
  3. return the minimum element of the stream
  4. navigate through element and return the name
// number of cats
        System.out.println("\nNumber of Cats");
        long numOfCats = petAnimals.stream()
            .filter(animal -> animal.getType().equals(Type.CAT))
            .count();
        System.out.println(numOfCats);
Enter fullscreen mode Exit fullscreen mode
  1. Turn the Collection into a stream
  2. Filter out the Objects based on Type into another stream
  3. return the number of elements in the stream

Discussion (0)

Forem Open with the Forem app