Stream API basic examples
Published on August 20, 2024
package ch.souradip.streamapi;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
record Employee(String name, Double salary, Date joiningDate, String gender){}
public class Main {
public static void main(String[] args) {
System.out.println("Steam API introduction");
List<Integer> numbers = Arrays.asList(5, 12, 7, 3, 19, 8, 4, 10, 14, 6);
List<Integer> filteredList = numbers.stream()
.filter(i -> i % 2 == 0)
.collect(Collectors.toList());
System.out.println(filteredList);
// Multiply by 2 each element
List<Integer> multipliedList = filteredList.stream()
.map(el -> el * 2)
.collect(Collectors.toList());
System.out.println(multipliedList);
// Select only passed student
List<Integer> marks = Arrays.asList(10, 50, 75, 35, 25, 20, 40);
List<Integer> passed = marks.stream()
.filter(i -> i > 35)
.collect(Collectors.toList());
System.out.println(passed);
// Add the 5 grace marks to all the failed student
List<Integer> graceMarks = marks.stream()
.filter(i -> i < 35)
.map(i -> i + 5)
.collect(Collectors.toList());
System.out.println(graceMarks);
/*
count()
Get the total number of failed student
*/
long failedStudentCount = marks.stream()
.filter(i -> i < 35)
.count();
System.out.println(failedStudentCount);
/*
Sorted()
- To sort the order of elements in the Stream
- Sorted according to the natural order
*/
// Sort the element from stream
List<Integer> sortedMarksAsc = marks.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedMarksAsc);
// Descending order
List<Integer> sortedMarksDesc= marks.stream()
.sorted((a, b) -> b.compareTo(a))
.collect(Collectors.toList());
System.out.println(sortedMarksDesc);
// sort based on length of string
List<String> words = Arrays.asList("apple", "grape", "honeydew", "kiwi", "lemon");
Comparator<String> c = (a, b) ->{
Integer l1 = a.length();
Integer l2 = b.length();
return Integer.compare(l1, l2);
};
List<String> sortedWordsDesc= words.stream()
.sorted((a, b) -> Integer.compare(b.length(), a.length()))
// .sorted(Comparator.comparingInt(String::length)) -- another way
.collect(Collectors.toList());
System.out.println(sortedWordsDesc);
/*
min()
max()
min(comparator) will return 1st element from the comparator result; (not the minimum value)
max(comparator) will return last element from the comparator result; (Not the maximum value)
*/
String minString = words.stream()
.min((a, b) -> Integer.compare(b.length(), a.length()))
.get();
System.out.println(minString);//output - honeydew
// MIN DOES NOT RETURN THE MIN ELEMENT IT RETURNS THE FIRST ELEMENT BASED ON COMPARATOR
String maxString = words.stream()
.max((a, b) -> Integer.compare(b.length(), a.length()))
.get();
System.out.println(maxString);//output - honeydew
// MAX DOES NOT RETURN THE MAX ELEMENT IT RETURNS THE LAST ELEMENT BASED ON COMPARATOR
// numbers --> 5, 12, 7, 3, 19, 8, 4, 10, 14, 6
Integer minNumber = numbers.stream()
.min((a, b) -> Integer.compare(a, b))
.get();
System.out.println(minNumber); // 19
Integer maxNumber = numbers.stream()
.max((a, b) -> Integer.compare(a, b))
.get();
System.out.println(maxNumber); // 3
/*
forEach()
- To perform an action for each element of this strem
- it is Terminal operation
*/
System.out.println("*** forEach() Start***");
numbers.stream().forEach(i -> System.out.println(i));
System.out.println("*** forEach() end ***");
/*
How to convert Stream of object into Arrays?
- toArray(); Terminal Operation
*/
Integer[] numsArray = numbers.stream().toArray(Integer[]::new);
System.out.println(Arrays.toString(numsArray));
/*
How to convert Array to Stream?
- Arrays.stream(array)
- Stream.of(args) : here args should be any types either arrays or any group of elements.
*/
int[] arr = new int[]{1,2,3,4,5};
Arrays.stream(arr).filter(i -> i % 2 == 0).forEach(System.out::println);
Stream.of(9, 8, 777, "a", "cc").map(i -> i + "**").forEach(System.out::println);
List<Employee> employees = Arrays.asList(
new Employee("John Doe", 75000.00, new Date(2020, 5, 15), "Male"),
new Employee("Jane Smith", 85000.00, new Date(2019, 3, 22), "Female"),
new Employee("Alice Johnson", 95000.00, new Date(2018, 11, 5), "Female"),
new Employee("Bob Brown", 70000.00, new Date(2021, 7, 19), "Male"),
new Employee("Charlie Davis", 80000.00, new Date(2022, 1, 10), "Male")
);
// Q1: Find the Employee who has the maximum salary
Employee maxSalaryPerson = employees.stream()
.max(Comparator.comparingDouble(Employee::salary))
.orElse(null); // Handle potential empty stream
System.out.println("Max salaried person => " + maxSalaryPerson);
// Q2: Find the Employee who has the second-highest salary
Optional<Employee> secondHighestSalariedPerson = employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary).reversed())
.skip(1)
.findFirst();
secondHighestSalariedPerson.ifPresent(employee ->
System.out.println("Second highest salaried person => " + employee)
);
// Q3: Find the employee who is the most senior based on joining date
Employee mostSeniorEmployee = employees.stream()
.min(Comparator.comparing(Employee::joiningDate))
.orElse(null); // Handle potential empty stream
System.out.println("Most senior person => " + mostSeniorEmployee);
// Q4: Count the employees based on gender
Map<String, Long> genderRatio = employees.stream()
.collect(Collectors.groupingBy(Employee::gender, Collectors.counting()));
System.out.println("Gender Ratio => " + genderRatio);
}
}