Partitioning Data with Java Streams

🚀 Java Streams in Action: Partitioning Data ! 👉 Partition employees into two groups - one earning above ₹50,000 and the others. i. Have you ever needed to split data into two groups based on a condition? ii. Here’s a simple example using Java Streams to partition employees based on salary. 🔍 Approach 👉 stream() Converts the list into a stream to perform functional-style operations. 👉 filter(Objects::nonNull) Removes any null objects from the list to avoid NullPointerException. 👉 collect(...) Terminal operation that transforms the stream into a collection (in this case, a Map). 👉 Collectors.partitioningBy(...) This is the key part 🔥 It splits the data into two groups based on a condition: true -> Employees earning more than ₹50,000 false -> Employees earning ₹50,000 or less ✔ Automatically groups into two categories ✔ Ideal for binary conditions (true/false) 📊 Output Structure true -> List of high-salary employees false -> List of other employees - Use partitioningBy when your condition results in only two groups. - If you need multiple groups (like department-wise), go for groupingBy. 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #JavaStreams #CodingInterview #BackendDevelopment #SpringBoot #Developers

  • text

public class StreamPractice { public static void main(String[] args) { List<Employee> listOfEmployees = List.of(new Employee("Suresh", "IT", 30000), new Employee("Ramesh", "IT", 45000), new Employee("Amit", "HR", 28000), new Employee("Neha", "HR", 34000), new Employee("Kiran", "BPO", 25000), new Employee("John", "Admin", 550000), new Employee("Suresh", "IT", 30000), new Employee("Amit", "HR", 29000), new Employee("Ruresh", "FieldWork", 350000), new Employee("Unknown", null, 50000)); //Partition employees into two groups - one earning above ₹50,000 and the other below. Map<Boolean, List<Employee>> map = listOfEmployees.stream().filter(Objects::nonNull) .collect(Collectors.partitioningBy(e -> e.getSalary() > 50000)); System.out.println("---------Employees with salary > 50000---------"); map.get(Boolean.TRUE).forEach(e -> System.out.println(e)); System.out.println("---------Employees with salary <= 50000--------"); map.get(Boolean.FALSE).forEach(e -> System.out.println(e)); } }

To view or add a comment, sign in

Explore content categories