Stream API Sample Examples

✅ 1. Filter Even Numbers

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

List<Integer> evens = numbers.stream()
                             .filter(n -> n % 2 == 0)
                             .collect(Collectors.toList());

System.out.println(evens); // Output: [2, 4, 6]


✅ 2. Convert to Uppercase

List<String> names = Arrays.asList("aftab", "neha", "ravi");

List<String> upperNames = names.stream()
                               .map(String::toUpperCase)
                               .collect(Collectors.toList());

System.out.println(upperNames); // Output: [AFTAB, NEHA, RAVI]


✅ 3. Sort Strings by Length

List<String> words = Arrays.asList("apple", "banana", "kiwi", "pear");

List<String> sorted = words.stream()
                           .sorted(Comparator.comparingInt(String::length))
                           .collect(Collectors.toList());

System.out.println(sorted); // Output: [kiwi, pear, apple, banana]


✅ 4. Find First Element Starting with 'A'

List<String> names = Arrays.asList("Ravi", "Aftab", "Nitin");

Optional<String> name = names.stream()
                             .filter(n -> n.startsWith("A"))
                             .findFirst();

System.out.println(name.orElse("No match")); // Output: Aftab


✅ 5. Sum of Squares

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);

int sumOfSquares = numbers.stream()
                          .map(n -> n * n)
                          .reduce(0, Integer::sum);

System.out.println(sumOfSquares); // Output: 30


✅ 6. Count Strings Longer Than 4 Letters

List<String> names = Arrays.asList("Java", "Spring", "AWS", "Hibernate");

long count = names.stream()
                  .filter(n -> n.length() > 4)
                  .count();

System.out.println(count); // Output: 2


✅ 7. Group Names by Starting Letter

List<String> names = Arrays.asList("Neha", "Nitin", "Aftab", "Ravi");

Map<Character, List<String>> grouped = names.stream()
    .collect(Collectors.groupingBy(name -> name.charAt(0)));

System.out.println(grouped);
// Output: {N=[Neha, Nitin], A=[Aftab], R=[Ravi]}


✅ 8. Remove Duplicates and Sort

List<Integer> nums = Arrays.asList(3, 2, 1, 2, 3, 4);

List<Integer> result = nums.stream()
                           .distinct()
                           .sorted()
                           .collect(Collectors.toList());

System.out.println(result); // Output: [1, 2, 3, 4]

✅ 9. Sum of two numbers

SumInterface sumInterface = (a, b) -> a + b;
int sum = sumInterface.sum(12, 15);
System.out.println(sum);
---
@FunctionalInterface
public interface SumInterface {
int sum(int a, int b);
}

 

✅ 10. Check if String is Empty

String str1 = "";
String str2 = "Aftab";

Predicate<String> isEmpty = str -> str.isEmpty();

System.out.println(isEmpty.test(str1));
System.out.println(isEmpty.test(str2));

✅ 11. Convert String to Uppercase or Lowercase

List<String> strList = Arrays.asList("Aftab", "Shaista", "Ayman", "Libran");
 strList.replaceAll(str -> str.toUpperCase());
System.out.println(strList);

 

✅ 12. Filter Even/Odd numbers

List<Integer> lstInt = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

List<Integer> even = lstInt.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());

System.out.println(even);

List<Integer> odd = lstInt.stream().filter(n -> n % 2 != 0).collect(Collectors.toList());

System.out.println(odd);

✅ 13. Sort strings alphabetically using a lambda

List<String> listStr = Arrays.asList("Mohit", "Rahul", "Aftab", "Vikas", "Neha", "Shallu", "Megha");
// Collections.sort(listStr); // Without collection

System.out.println(listStr);

List<String> newStr = listStr.stream().sorted().collect(Collectors.toList());

System.out.println(newStr);

 

✅ 14. Find the average of doubles using a lambda


List<Double> listDouble = Arrays.asList(12.03, 11.44, 66.55, 65.44, 7.88);

OptionalDouble avg = listDouble.stream().mapToDouble(Double::doubleValue).average();

System.out.println(avg);

✅ 15. Remove integer duplicates

List<Integer> listInt = Arrays.asList(1, 2, 2, 4, 5, 3, 2, 9, 9);
List<Integer> listDistinctInt = listInt.stream().distinct().collect(Collectors.toList());
System.out.println(listDistinctInt);

✅ 16. Concatenate two strings


String s1 = "Aftab";
String s2 = "Ahmed";

BiFunction<String, String, String> concatenate = (ss1, ss2) -> ss1 + ss2;

String newString = concatenate.apply(s1, s2);

System.out.println(newString);

✅ 17. Find max and min in a list of Integers using a lambda

List<Integer> listInt1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

Optional<Integer> max = listInt1.stream().max((x, y) -> x.compareTo(y));
Optional<Integer> min = listInt1.stream().min((x, y) -> x.compareTo(y));

System.out.println(max.orElse(null));
System.out.println(min.orElse(null));


✅ 17. Multiply and sum list elements


 intValue = listInt1.stream().reduce(1, (x, y) -> x * y).intValue();
System.out.println(intValue);

 intValue2 = listInt1.stream().reduce(0, (x, y) -> x + y).intValue();
System.out.println(intValue2);

✅ 18. Sort a list of objects based on a specific attribute

class Student {

private String sName, sClass;
private int sAge;

public Student(String sName, String sClass, int sAge) {
super();
this.sName = sName;
this.sClass = sClass;
this.sAge = sAge;
}
// Getter or Setters
}

----

List<Student> lStudent = new ArrayList<>();
lStudent.add(new Student("Aftab", "Science", 30));
lStudent.add(new Student("Danish", "Art", 17));
lStudent.add(new Student("Ayman", "Commerce", 21));
lStudent.add(new Student("Libran", "Science", 24));
lStudent.add(new Student("Shaista", "Art", 31));

---

for (Student student : lStudent) {
System.out.println(student.getsName() + " " + student.getsClass() + " " + student.getsAge());
}

lStudent.sort(Comparator.comparing(Student::getsName));

for (Student student : lStudent) {
System.out.println(student.getsName() + " " + student.getsClass() + " " + student.getsAge());
}

✅ 19. flatMap() Example – Flattening Nested Lists

List<List<String>> nestedList = Arrays.asList(
    Arrays.asList("Java", "Spring"),
    Arrays.asList("AWS", "Docker"),
    Arrays.asList("Kubernetes")
);

List<String> flatList = nestedList.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

System.out.println(flatList);
// Output: [Java, Spring, AWS, Docker, Kubernetes]

✅ Why use flatMap()?

  • Converts Stream<Stream<T>> to a single Stream<T>
  • Ideal for flattening nested collections

✅ 20. CollectingAndThen() Example – Make List Unmodifiable

List<String> names = Arrays.asList("Aftab", "Neha", "Ravi");

List<String> unmodifiableList = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.collectingAndThen(
        Collectors.toList(),
        Collections::unmodifiableList
    ));

System.out.println(unmodifiableList);
// Output: [AFTAB, NEHA, RAVI]
unmodifiableList.add("Test"); // Throws UnsupportedOperationException


✅ Why use collectingAndThen()?

  • Performs a post-processing transformation after collecting
  • Useful to wrap collections (e.g., make them immutable)
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.