Skip to main content

Stream API

Stream API

Count

List<Integer> list = Arrays.asList(10, 5, 3, 9, 5, 4, 6);
long count = list.stream().count();

Reduce

long sum = list.stream().reduce(0, (a,b)->a+b);// Returns the sum
int sum  = list.stream().reduce(0,Integer::sum);

long facto = list.stream().reduce(1, (a,b)->a*b);// Returns the factorial
long evenSum = list.stream().reduce(0, (t, u) ->(u % 2 == 0)?t + u: t);// Sum of even numbers

BinaryOperator<Integer> binOp = new BinaryOperator<Integer>() {
    @Override
    public Integer apply(Integer previous, Integer current) {
    if (current % 2 == 0) {
        return previous + current;
    }
        return previous;
    }
};
long count = list.stream().reduce(0, binOp);
System.out.println(count);

int min = list.stream().reduce(list.get(0),Integer::min);
int max = list.stream().reduce(list.get(0),Integer::max);

All Match

boolean x = list.stream().allMatch(n->n%0==1); // true if all are odd numbers

Any Match

boolean x = list.stream().anyMatch(n->n%0==1); // true if one is odd numbers

None Match

boolean x = list.stream().noneMatch(n->n<0);

Distinct

Stream<Integer> x = list.stream().distinct(); // Returns non duplicate stream

Drop While

List<Integer> list = Arrays.asList( 10, 8, 7, 5, 3, 6,10);
Collections.sort(list);
list = list.stream().dropWhile(n->n<8).collect(Collectors.toList());;
System.out.println(list);// [8, 10, 10]

Stream<String> listStream = Stream.of("hello", "educative", "hi", "edpresso");
List<String> strList = listStream.dropWhile(s -> s.length() >= 5).collect(Collectors.toList());
System.out.println(strList);// [hi, edpresso]

Sorted

List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
list.stream().sorted().forEach(System.out::println);

Flat Map

When we have stream of stream data we can use flat map to map to a stream

List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 8, 7, 5, 3, 6, 10),Arrays.asList(10, 8, 7, 5, 3, 6, 10),Arrays.asList(10, 8, 7, 5, 3, 6, 10));
List<Integer> list1 = list.stream().flatMap(n->n.stream()).collect(Collectors.toList());
System.out.println(list1);

Limit

List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
List<Integer> y = list.stream().sorted().limit(5).collect(Collectors.toList());
System.out.println(y);//[3, 5, 6, 7, 8]

Skip

List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
List<Integer> y = list.stream().skip(3).collect(Collectors.toList());
System.out.println(y);

Take While

list.stream().sorted().takeWhile(n -> n < 8).collect(Collectors.toList());

Sorting Using Comparator

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Application {
    public static void main(String[] args) {

        List<Student> list = Arrays.asList(new Student(10, "Dayalan"), new Student(9, "Sajini"),
                new Student(11, "Iniyal"));
        //Method 1
        list.stream().sorted((o1, o2) -> (o1.age> o2.age)?1:-1).forEach(System.out::println);
        //Method 2
        list.stream().sorted((o1, o2) -> Integer.compare(o1.age, o2.age)).forEach(System.out::println);
        //Method 3
        list.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
        //Method 4
        list.sort(Comparator.comparing(Student::getAge));
        System.out.println(list);
    }
}

class Student {

    int age;
    String name;

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "{\"age\":\"" + age + "\", \"name\":\"" + name + "\"}";
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Multiple Fields for Sorting

class Address implements Comparable<Address> {
    private Long no;
    private String street;
    private String city;

    public Long getNo() {
        return no;
    }

    public void setNo(Long no) {
        this.no = no;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public int compareTo(Address o) {
        Comparator<Address> streetComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet());
        Comparator<Address> cityComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet());
        return Comparator.comparingLong(Address::getNo).thenComparing(streetComp).thenComparing(cityComp).compare(this,
                o);
    }

}

Stream.Collections Class


List<String> list = Arrays.asList("2", "3", "5", "6", "10", "10", "11", "20", "52");

toList()

       
List<String> numMorethan8 = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.toList());
System.out.println(numMorethan8);
// Collected as a List, Output : [10, 10, 11, 20, 52]

toSet()

Set<String> numMorethanSet = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.toSet());
System.out.println(numMorethanSet);
// Collected as a non duplicate List out put : [11, 52, 20, 10]

joining()

String x = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.joining());
System.out.println(x);
// Collected as a List Output : 1010112052

List<Integer> numList = Arrays.asList(2,3,5,6,10,10,11,20,52);
String str= numList.stream().map(n->n.toString()).collect(Collectors.joining(","));
System.out.println(str);
// Collected as a List Output : 2,3,5,6,10,10,11,20,52

groupingBy()

List<Integer> numList = Arrays.asList(2, 3, 5, 6, 10, 10, 11, 20, 52);
Map<Object, List<Integer>> str = numList.stream()
    .collect(Collectors.groupingBy(n -> n % 2 == 0 ? "Even" : "Odd"));
System.out.println(str);
// Collected as a List Output : {"Even":[2, 6, 10, 10, 20, 52], "Odd":[3, 5, 11]}

List<Student> listStudent = new ArrayList<Student>();
listStudent.add(new Student(10, "Dayalan"));
listStudent.add(new Student(10, "Sajini"));
listStudent.add(new Student(20, "Iniyal"));
listStudent.add(new Student(20, "Thambi"));
listStudent.add(new Student(25, "Anna"));
listStudent.add(new Student(25, "Thiya"));
Map<Integer, List<Student>> studentMapByAge = listStudent.stream().collect(Collectors.groupingBy(Student::getAge));
System.out.println(studentMapByAge);

//{20:[{"age":"20", "name":"Iniyal"}, {"age":"20", "name":"Thambi"}], 25:[{"age":"25", "name":"Anna"}, {"age":"25", "name":"Thiya"}], 10:[{"age":"10", "name":"Dayalan"}, {"age":"10", "name":"Sajini"}]}

averagingInt()

Double averageAge = listStudent.stream().collect(Collectors.averagingInt(Student::getAge));
System.out.println(averageAge);

partitionBy()

Map<Boolean, List<Student>> x = listStudent.stream().collect(Collectors.partitioningBy(n->n.getAge()>18));
System.out.println(x);
/*
 * {false:[{"age":"10", "name":"Dayalan"}, {"age":"10", "name":"Sajini"}],
 * true:[{"age":"20", "name":"Iniyal"}, {"age":"20", "name":"Thambi"},
 * {"age":"25", "name":"Anna"}, {"age":"25", "name":"Thiya"}]}
 */

counting()

Long x = listStudent.stream().collect(Collectors.counting());
System.out.println(x);

maxBy()

Optional<Student> x = listStudent.stream().collect(Collectors.maxBy(Comparator.comparing(Student::getAge)));
System.out.println(x); // {"age":"25", "name":"Anna"}

toMap()

Map<String, Integer> x = listStudent.stream().collect(Collectors.toMap(Student::getName,Student::getAge ));
System.out.println(x); // {Dayalan=10, Iniyal=20, Sajini=10, Thambi=20, Thiya=25, Anna=25}


Comments

Popular posts from this blog

Spring Boot 4 Ready

Spring Boot 4.x Features Explained:  Java 25, AI Agents, MCP, Resilience, gRPC & Cloud Native Evolution Building on the massive architectural shift introduced in version 3, Spring Boot 4.x bridges the gap between traditional enterprise stability and the rapid demands of modern cloud architecture and AI integration. While Spring Boot 3 introduced the foundations for GraalVM Native Images and Virtual Threads , Spring Boot 4 takes these capabilities mainstream, introduces native resilience patterns, and upgrades the underlying Spring ecosystem. Spring Boot 4 Major Theme: Modern enterprise development with cloud-native architecture, AI integration, improved resilience, better modularity, and optimized JVM performance. Table of Contents 1. Upgraded Foundation & Baselines 2. Built-in Core Resilience Features 3. First-Class Agentic AI & Model Context Protocol (MCP) 4. Native API Versioning Strategy 5. Modern...

Most questions in 2025

Java Spring Boot Senior Engineer Interview Questions & Answers A complete interview preparation guide for Senior Java Engineers, Spring Boot Developers, and Backend Technical Leads covering Java, Spring Boot, Microservices, Cloud, Database, Security, and Performance Engineering concepts. Target Audience: Senior Java Developers Spring Boot Engineers Microservice Architects Backend Technical Leads Table of Contents 1. Describe Yourself 2. RESTful APIs and Standards 3. Latest Spring Boot Version & Features 4. Java Optional 5. WebFlux Reactive Programming 6. WebFlux Retry Mechanism 7. WebFlux Pagination APIs 8. Circuit Breaker 9. Resilience Patterns 10. Rate Limiter 1. Describe Yourself A senior engineer introduction should highlight technical experience, architecture knowledge, ownership, and problem-solving capabilities. Sample Answer I am a Java backend engineer with 7+ years of experience desi...

Data Structure

Java Data Structures A highly-scannable architectural cheat sheet for developers and technical interviews. 1. Linear vs. Non-Linear: The Core Division Data Structure Classification Hierarchy ┌───────────────────────┐ │ Data Structures │ └───────────┬───────────┘ │ ┌───────────────┴───────────────┐ ▼ ▼ ┌────────────────────┐ ┌────────────────────┐ │ Linear (Seq) │ │ Non-Linear │ └──────────┬─────────┘ └──────────┬─────────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ▼ ▼ ▼ ▼ [Static] [Dynamic] [Trees] [Graphs] (Array) (Queue, Stack) (BST) (Network) ...