Stream API in Java 8: Filtering, Mapping, Sorting, and Counting

🚀 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗝𝗮𝘃𝗮 𝟴 𝗦𝘁𝗿𝗲𝗮𝗺 𝗔𝗣𝗜 𝘄𝗶𝘁𝗵 𝗢𝗻𝗲 𝗖𝗼𝗺𝗽𝗹𝗲𝘁𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 The 𝗦𝘁𝗿𝗲𝗮𝗺 𝗔𝗣𝗜, introduced in Java 8, allows developers to process collections in a 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗮𝗻𝗱 𝗲𝗳𝗳𝗶𝗰𝗶𝗲𝗻𝘁 𝘄𝗮𝘆. It helps write 𝗰𝗹𝗲𝗮𝗻, 𝗿𝗲𝗮𝗱𝗮𝗯𝗹𝗲, 𝗮𝗻𝗱 𝗰𝗼𝗻𝗰𝗶𝘀𝗲 𝗰𝗼𝗱𝗲 when performing operations on collections. Below is a single example demonstrating multiple Stream operations like `filter`, `map`, `sorted`, `count`, and `collect`. 💻 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 ```java import java.util.*; import java.util.stream.*; public class StreamExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3, 6); numbers.stream() .filter(n -> n > 3) .forEach(n -> System.out.println("Filter (>3): " + n)); numbers.stream() .map(n -> n * 2) .forEach(n -> System.out.println("Map (*2): " + n)); numbers.stream() .sorted() .forEach(n -> System.out.println("Sorted: " + n)); long count = numbers.stream() .filter(n -> n > 3) .count(); System.out.println("Count (>3): " + count); List<Integer> result = numbers.stream() .filter(n -> n > 3) .collect(Collectors.toList()); System.out.println("Collected List: " + result); } } ``` 📌 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 🔹 𝗳𝗶𝗹𝘁𝗲𝗿() – Filters elements based on a condition 🔹 𝗺𝗮𝗽() – Transforms elements into another form 🔹 𝘀𝗼𝗿𝘁𝗲𝗱() – Sorts elements in ascending order 🔹 𝗳𝗼𝗿𝗘𝗮𝗰𝗵() – Performs an action on each element 🔹 𝗰𝗼𝘂𝗻𝘁() – Counts elements in the stream 🔹 𝗰𝗼𝗹𝗹𝗲𝗰𝘁() – Collects results into a collection like a List The Stream API makes Java programs more powerful, readable, and easier to maintain. #Java #Java8 #StreamAPI #Programming #SoftwareDevelopment #Coding #Developers

To view or add a comment, sign in

Explore content categories