Master IntStream in Java: From Basics to Real Use Case
IntStream is a primitive stream in Java (from java.util.stream) that works specifically with int values. π It is part of Java 8 Streams and helps you: Avoid boxing/unboxingβ¦
IntStream is a primitive stream in Java (from java.util.stream) that works specifically with int values.
π It is part of Java 8 Streams and helps you:
- Avoid boxing/unboxing (
Integerβint) - Perform fast numeric operations like
sum(),average(),max()
How IntStream is Created
β Common Ways
IntStream.of(...)Arrays.stream(int[])list.stream().mapToInt(...)
Complete Example (Interview Ready)
Problem:
Find the average salary of employees whose age > 30
Full Code Example
import java.util.*;
import java.util.stream.*;class Employee {
int age;
int salary; Employee(int age, int salary) {
this.age = age;
this.salary = salary;
} public int getAge() {
return age;
} public int getSalary() {
return salary;
}
}public class Main {
public static void main(String[] args) { List<Employee> employees = Arrays.asList(
new Employee(25, 30000),
new Employee(35, 50000),
new Employee(40, 70000)
); double avgSalary = employees.stream()
.filter(e -> e.getAge() > 30) // Stream<Employee>
.mapToInt(e -> e.getSalary()) // IntStream β
.average() // OptionalDouble
.orElse(0); System.out.println("Average Salary: " + avgSalary);
}
}
import java.util.*;
import java.util.stream.*;class Employee {
int age;
int salary; Employee(int age, int salary) {
this.age = age;
this.salary = salary;
} public int getAge() {
return age;
} public int getSalary() {
return salary;
}
}public class Main {
public static void main(String[] args) { List<Employee> employees = Arrays.asList(
new Employee(25, 30000),
new Employee(35, 50000),
new Employee(40, 70000)
); double avgSalary = employees.stream()
.filter(e -> e.getAge() > 30) // Stream<Employee>
.mapToInt(e -> e.getSalary()) // IntStream β
.average() // OptionalDouble
.orElse(0); System.out.println("Average Salary: " + avgSalary);
}
}
Step-by-Step Flow
employees.stream()
βStream<Employee>.filter(e -> e.getAge() > 30)
β stillStream<Employee>.mapToInt(e -> e.getSalary())
β π₯ converts toIntStream.average()
β returnsOptionalDouble.orElse(0)
β gives finaldouble
Output
Average Salary: 60000.0
Another Simple Example (Very Important)
IntStream numbers = IntStream.of(10, 20, 30, 40);int sum = numbers.sum();System.out.println(sum); // 100
Key Interview Points
IntStreamis for primitive int values- Created using:
mapToInt()IntStream.of()Arrays.stream()
- Supports operations:
sum(),average(),max(),min()
Final One-Line Answer (Interview)
β
IntStreamis a primitive stream of integers used for efficient numeric operations, typically created usingmapToInt()when converting from object streams.β