DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Java Stream API

Java Stream API

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

A N M Bazlur Rahman user avatar by
A N M Bazlur Rahman
CORE ·
Jul. 17, 15 · Tutorial
Like (12)
Save
Tweet
Share
7.66K Views

Join the DZone community and get the full member experience.

Join For Free

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

API Stream (computing) Java (programming language)

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.

Popular on DZone

  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB
  • Building a Scalable Search Architecture
  • Utilize OpenAI API to Extract Information From PDF Files

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: