Java Stream API

DZone 's Guide to

Java Stream API

The Java Stream API is awesome. If you haven't used it yet, this tutorial will help you find your way.

· Java Zone ·
Free Resource

I have been using Java Stream API massively these days. So I thought, why not write a short tutorial on it.

So what is steam anyway?

Don’t be confused with InputStream or OutputStream of Java IO. Stream are complete different thing in Java 8.

A stream basically represents a sequence of elements and provide a rich set of operations to compute those elements.

Its common to do bulk operation in our day to day business application. So normally we do use for loops and collections to do that, we iterate over the collection and then write if then else code and various variables come into play and we get a big chunk of ugly and sequential code.

We do the same thing using stream API but can abstract things in to a very high level using lambda and functional approach and write more elegant understandable and clean code. After having certain abstraction, we can do certain optimization, like we might want to go parallel, which was never easy before.

Well enough talk, lets do some code example –

1. First of all, lets remove regular for loop with IntStream. What I want to do is, print 1 to 10-

IntStream.range(0, 10)
          .forEach(value -> System.out.println(value));

Or just using method reference-

IntStream.range(0, 5)

2. I want to count number of elements in the list –

List<Integer> list = IntStream.range(1, 100)

3. I want to find average of all elements in the list –

Double avarage = list.stream()
   .collect(Collectors.averagingInt(item -> item));

4. I want to get complete summery of the list

IntSummaryStatistics intSummaryStatistics = list.stream()
  .collect(Collectors.summarizingInt(value -> value));


//IntSummaryStatistics{count=99, sum=4950, min=1, average=50.000000, max=99}

5. Create a map out of the list

Map<Integer, Integer> map = list.stream()
  .collect(Collectors.toMap(p -> p, q -> q * 3));
//{1=3, 2=6, 3=9, 4=12}

6. I want to get the maximum number of the list

// first make a random integer list 
List<Integer> randomInts = new Random().ints(-100, 100).limit(250).boxed().collect(Collectors.toList()); 

Optional<Integer> max = randomInts.stream().reduce(Math::max); 
max.ifPresent(value -> System.out.println(value)); 

// or  
max.ifPresent(System.out::println);// method reference 

7. Say I have an array of names and I want to count all the name that starts wit ‘C’

String[] names = {"Fred Edwards", 
                "Anna Cox", 
                "Deborah Patterson", 
                "Ruth Torres", 
                "Shawn Powell", 
                "Rose Thompson", 
                "Rachel Barnes", 
                "Eugene Ramirez", 
                "Earl Flores", 
                "Janice Reed", 
                "Sarah Miller", 
                "Patricia Kelly", 
                "Carl Hall", 
                "Craig Wright", 
                "Martha Phillips", 
                "Thomas Howard", 
                "Steve Martinez", 
                "Diana Bailey", 
                "Kathleen Hughes", 
                "Russell Anderson", 
                "Theresa Perry"}; 

long c = Arrays.asList(names) 
                .filter(s -> s.startsWith("C")) 

8. Say I want to make all the name upper case and the sort and then print


An advance example

Say I have a class named Person ->

public class Person { 
    private String name; 
    private int age; 

    public String getName() { 
        return name; 

    public Person setName(String name) { 
        this.name = name; 
        return this; 

    public int getAge() { 
        return age; 

    public Person setAge(int age) { 
        this.age = age; 
        return this; 

    Person(String name, int age) { 
        this.name = name; 
        this.age = age; 

    public String toString() { 
        return name; 

9 . I want to get persons  group by age

Map<Integer, List<Person>> collect = persons 

10  I want to get average age of all the persons

Double collect1 = persons 

To be continued...

java, stream

Published at DZone with permission of A. N. M. Bazlur Rahman , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}