# Java Streams and Functional Programming

Java Streams provide a powerful way to process collections using functional programming concepts. Here’s a basic example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
.filter(name -> name.length() > 4)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filteredNames); // [ALICE, CHARLIE, DAVID]
}
}

Advanced stream operations for complex data processing:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class AdvancedStreams {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("John", 25, "Developer"),
new Person("Jane", 30, "Designer"),
new Person("Bob", 25, "Developer")
);
// Group by profession and count
Map<String, Long> professionCount = people.stream()
.collect(Collectors.groupingBy(
Person::getProfession,
Collectors.counting()
));
// Find average age by profession
Map<String, Double> avgAgeByProfession = people.stream()
.collect(Collectors.groupingBy(
Person::getProfession,
Collectors.averagingInt(Person::getAge)
));
}
}

Streams make data processing more readable and efficient compared to traditional loops.

Running Java Streams
javac StreamExample.java && java StreamExample
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments