Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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)
         .forEach(System.out::println);

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

List<Integer> list = IntStream.range(1, 100)
    .boxed()
    .collect(Collectors.toList());
list.stream().count();

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));

System.out.println(intSummaryStatistics);

//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));
System.out.println(map);
//{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) 
                .stream() 
                .filter(s -> s.startsWith("C")) 
                .count();

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

Arrays.asList(names) 
                .stream() 
                .map(String::toUpperCase) 
                .sorted() 
                .forEach(System.out::println);

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; 
    } 

    @Override 
    public String toString() { 
        return name; 
    } 
} 

9 . I want to get persons  group by age

Map<Integer, List<Person>> collect = persons 
                .stream() 
                .collect(Collectors.groupingBy(Person::getAge)); 

10  I want to get average age of all the persons

Double collect1 = persons 
                .stream() 
                .collect(Collectors.averagingInt(Person::getAge)); 


To be continued...

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
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.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}