├── SteamsOnProductOrders.java ├── StreamBeginnerQuestions.java ├── StreamMediumQuestions.java ├── StreamScenarioPart1.java └── StreamsOnStudentData.java /SteamsOnProductOrders.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.streams; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.stream.Collectors; 8 | 9 | import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQProperties; 10 | 11 | class Product { 12 | private String productId; 13 | private String productName; 14 | private String category; 15 | private double price; 16 | private String currency; 17 | private String eventTime; // ISO date string 18 | private String eventType; // e.g. "PRICE_UPDATE" 19 | 20 | // Constructors 21 | public Product() { 22 | } 23 | 24 | public Product(String productId, String productName, String category, double price, String currency, 25 | String eventTime, String eventType) { 26 | this.productId = productId; 27 | this.productName = productName; 28 | this.category = category; 29 | this.price = price; 30 | this.currency = currency; 31 | this.eventTime = eventTime; 32 | this.eventType = eventType; 33 | } 34 | 35 | public String getProductId() { 36 | return productId; 37 | } 38 | 39 | public void setProductId(String productId) { 40 | this.productId = productId; 41 | } 42 | 43 | public String getProductName() { 44 | return productName; 45 | } 46 | 47 | public void setProductName(String productName) { 48 | this.productName = productName; 49 | } 50 | 51 | public String getCategory() { 52 | return category; 53 | } 54 | 55 | public void setCategory(String category) { 56 | this.category = category; 57 | } 58 | 59 | public double getPrice() { 60 | return price; 61 | } 62 | 63 | public void setPrice(double price) { 64 | this.price = price; 65 | } 66 | 67 | public String getCurrency() { 68 | return currency; 69 | } 70 | 71 | public void setCurrency(String currency) { 72 | this.currency = currency; 73 | } 74 | 75 | public String getEventTime() { 76 | return eventTime; 77 | } 78 | 79 | public void setEventTime(String eventTime) { 80 | this.eventTime = eventTime; 81 | } 82 | 83 | public String getEventType() { 84 | return eventType; 85 | } 86 | 87 | public void setEventType(String eventType) { 88 | this.eventType = eventType; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return "Product [productId=" + productId + ", productName=" + productName + ", category=" + category 94 | + ", price=" + price + ", currency=" + currency + ", eventTime=" + eventTime + ", eventType=" 95 | + eventType + "]"; 96 | } 97 | 98 | } 99 | 100 | class Order { 101 | private String orderId; 102 | private String productId; 103 | private String userId; 104 | private double orderAmount; 105 | private int quantity; 106 | private String paymentMode; 107 | private String orderStatus; // e.g. "PLACED", "CANCELLED" 108 | private String source; // e.g. "WEB", "MOBILE_APP", "POS" 109 | private String country; 110 | private String eventTime; // ISO date string 111 | 112 | public Order() { 113 | } 114 | 115 | public Order(String orderId, String productId, String userId, double orderAmount, int quantity, String paymentMode, 116 | String orderStatus, String source, String country, String eventTime) { 117 | this.orderId = orderId; 118 | this.productId = productId; 119 | this.userId = userId; 120 | this.orderAmount = orderAmount; 121 | this.quantity = quantity; 122 | this.paymentMode = paymentMode; 123 | this.orderStatus = orderStatus; 124 | this.source = source; 125 | this.country = country; 126 | this.eventTime = eventTime; 127 | } 128 | 129 | public String getOrderId() { 130 | return orderId; 131 | } 132 | 133 | public void setOrderId(String orderId) { 134 | this.orderId = orderId; 135 | } 136 | 137 | public String getProductId() { 138 | return productId; 139 | } 140 | 141 | public void setProductId(String productId) { 142 | this.productId = productId; 143 | } 144 | 145 | public String getUserId() { 146 | return userId; 147 | } 148 | 149 | public void setUserId(String userId) { 150 | this.userId = userId; 151 | } 152 | 153 | public double getOrderAmount() { 154 | return orderAmount; 155 | } 156 | 157 | public void setOrderAmount(double orderAmount) { 158 | this.orderAmount = orderAmount; 159 | } 160 | 161 | public int getQuantity() { 162 | return quantity; 163 | } 164 | 165 | public void setQuantity(int quantity) { 166 | this.quantity = quantity; 167 | } 168 | 169 | public String getPaymentMode() { 170 | return paymentMode; 171 | } 172 | 173 | public void setPaymentMode(String paymentMode) { 174 | this.paymentMode = paymentMode; 175 | } 176 | 177 | public String getOrderStatus() { 178 | return orderStatus; 179 | } 180 | 181 | public void setOrderStatus(String orderStatus) { 182 | this.orderStatus = orderStatus; 183 | } 184 | 185 | public String getSource() { 186 | return source; 187 | } 188 | 189 | public void setSource(String source) { 190 | this.source = source; 191 | } 192 | 193 | public String getCountry() { 194 | return country; 195 | } 196 | 197 | public void setCountry(String country) { 198 | this.country = country; 199 | } 200 | 201 | public String getEventTime() { 202 | return eventTime; 203 | } 204 | 205 | public void setEventTime(String eventTime) { 206 | this.eventTime = eventTime; 207 | } 208 | 209 | @Override 210 | public String toString() { 211 | return "Order [orderId=" + orderId + ", productId=" + productId + ", userId=" + userId + ", orderAmount=" 212 | + orderAmount + ", quantity=" + quantity + ", paymentMode=" + paymentMode + ", orderStatus=" 213 | + orderStatus + ", source=" + source + ", country=" + country + ", eventTime=" + eventTime + "]"; 214 | } 215 | 216 | } 217 | 218 | class MockDataUtil { 219 | 220 | public static List getMockProducts() { 221 | List products = new ArrayList<>(); 222 | 223 | products.add(new Product("P12345", "Wireless Mouse", "Electronics", 1499.00, "INR", "2025-04-22T10:05:00Z", 224 | "PRICE_UPDATE")); 225 | 226 | products.add(new Product("P67890", "Gaming Keyboard", "Electronics", 3499.00, "INR", "2025-04-22T09:55:00Z", 227 | "PRICE_UPDATE")); 228 | 229 | products.add(new Product("P11111", "Bluetooth Speaker", "Electronics", 1999.00, "INR", "2025-04-22T09:50:00Z", 230 | "PRICE_UPDATE")); 231 | 232 | products.add(new Product("P22222", "Fitness Tracker", "Wearables", 2999.00, "INR", "2025-04-22T10:00:00Z", 233 | "PRICE_UPDATE")); 234 | 235 | return products; 236 | } 237 | 238 | public static List getMockOrders() { 239 | List orders = new ArrayList<>(); 240 | 241 | orders.add(new Order("O98765", "P12345", "U67890", 2998.00, 2, "UPI", "PLACED", "MOBILE_APP", "IN", 242 | "2025-04-22T10:06:12Z")); 243 | 244 | orders.add(new Order("O54321", "P12345", "U12345", 1499.00, 1, "CREDIT_CARD", "PLACED", "WEB", "IN", 245 | "2025-04-22T10:06:30Z")); 246 | 247 | orders.add(new Order("O22222", "P67890", "U33333", 3499.00, 1, "NET_BANKING", "PLACED", "WEB", "IN", 248 | "2025-04-22T10:07:12Z")); 249 | 250 | orders.add(new Order("O98765", "P12345", "U67890", 0.00, 0, "UPI", "CANCELLED", "MOBILE_APP", "IN", 251 | "2025-04-22T10:10:45Z")); 252 | 253 | orders.add(new Order("O45678", "P67890", "U11111", 3499.00, 1, "CASH", "PLACED", "POS", "IN", 254 | "2025-04-22T10:07:30Z")); 255 | 256 | orders.add(new Order("O45679", "P67890", "U11112", 3499.00, 1, "CASH", "PLACED", "POS", "IN", 257 | "2025-04-22T10:07:45Z")); 258 | 259 | orders.add(new Order("O45680", "P67890", "U11113", 3499.00, 1, "CASH", "PLACED", "POS", "IN", 260 | "2025-04-22T10:08:00Z")); 261 | 262 | orders.add(new Order("O99999", "P22222", "U98765", 2999.00, 1, "UPI", "PLACED", "WEB", "IN", 263 | "2025-04-22T09:59:00Z")); 264 | 265 | orders.add(new Order("O10001", "P11111", "U55555", 1999.00, 1, "CREDIT_CARD", "PLACED", "MOBILE_APP", "IN", 266 | "2025-04-22T10:09:00Z")); 267 | 268 | orders.add(new Order("O10001", "P11111", "U55555", 1999.00, 1, "CREDIT_CARD", "PLACED", "WEB", "IN", 269 | "2025-04-22T10:09:10Z")); 270 | 271 | return orders; 272 | } 273 | } 274 | 275 | public class SteamsOnProductOrders { 276 | public static void main(String[] args) { 277 | // 1. Get all orders placed via Mobile 278 | List mobileAppList = MockDataUtil.getMockOrders().stream() 279 | .filter(o -> o.getSource().toLowerCase().contains("mobile")).collect(Collectors.toList()); 280 | System.out.println("1. Get all orders placed via Mobile: "+mobileAppList.size()); 281 | System.out.println(""); 282 | 283 | // 2. List all the product names 284 | List prodcutNamesList = MockDataUtil.getMockProducts().stream().map(p -> p.getProductName()) 285 | .collect(Collectors.toList()); 286 | System.out.println("2. List all the product names: "+prodcutNamesList); 287 | System.out.println(""); 288 | 289 | // 3. Count the number of orders placed for each product. 290 | Map numberOfOrdersPerProduct = MockDataUtil.getMockOrders().stream() 291 | .collect(Collectors.groupingBy(o -> o.getProductId(), Collectors.counting())); 292 | System.out.println("3. Count the number of orders placed for each product: "+numberOfOrdersPerProduct); 293 | System.out.println(""); 294 | 295 | // 4. Find the total revenue generated by "Gaming Keyboard" orders. 296 | Product gamingProduct = MockDataUtil.getMockProducts().stream() 297 | .filter(p -> p.getProductName().toLowerCase().equals("gaming keyboard")).findFirst().get(); 298 | 299 | Double revenueGeneratedByGamingKeyboards = MockDataUtil.getMockOrders().stream() 300 | .filter(o -> o.getProductId().equals(gamingProduct.getProductId())) 301 | .collect(Collectors.summingDouble(o -> o.getOrderAmount())); 302 | System.out.println("4. Find the total revenue generated by \"Gaming Keyboard\" orders: "+ revenueGeneratedByGamingKeyboards); 303 | System.out.println(""); 304 | //5. Get a distinct list of payment methods used in the orders. 305 | List paymentMethodsList = MockDataUtil.getMockOrders().stream().map(o -> o.getPaymentMode()).distinct() 306 | .toList(); 307 | System.out.println("5. Get a distinct list of payment methods used in the orders: "+paymentMethodsList); 308 | System.out.println(""); 309 | 310 | //6. Get the top 2 products with the highest price. 311 | List top2ProductsWithHighestPrice = MockDataUtil.getMockProducts().stream() 312 | .sorted((o1, o2) -> o1.getPrice() < o2.getPrice() ? 1 : -1).limit(2).toList(); 313 | System.out.println("6. Get the top 2 products with the highest price: "+top2ProductsWithHighestPrice); 314 | System.out.println(""); 315 | 316 | //7️. Detect duplicate orders (same orderId) and list them. 317 | List duplicateOrdersList = MockDataUtil.getMockOrders().stream().collect(Collectors.groupingBy(o -> o.getOrderId())) 318 | .entrySet() 319 | .stream() 320 | .filter(map -> map.getValue().size() > 1) 321 | .flatMap(o -> o.getValue().stream()) 322 | .collect(Collectors.toList()); 323 | System.out.println("7: Detect duplicate orders (same orderId) and list them: "+duplicateOrdersList); 324 | System.out.println(""); 325 | 326 | // 8.For each product, find total quantity sold across all orders. 327 | Map eachProductTotalQuanity = MockDataUtil.getMockOrders().stream() 328 | .collect(Collectors.groupingBy(o -> o.getProductId(), Collectors.summingInt(p -> p.getQuantity()))); 329 | 330 | System.out.println("8. For each product, find total quantity sold across all orders: "+eachProductTotalQuanity); 331 | System.out.println(""); 332 | //9️ Find the product whose total revenue is highest. 333 | Map productIdNameMap = MockDataUtil.getMockProducts().stream() 334 | .collect(Collectors.toMap(Product::getProductId, Product::getProductName)); 335 | 336 | 337 | String productNameString = MockDataUtil.getMockOrders().stream() 338 | .collect(Collectors.groupingBy(o -> o.getProductId(), Collectors.summingDouble(p -> p.getOrderAmount()))) 339 | .entrySet() 340 | .stream() 341 | .max(Map.Entry.comparingByValue()) 342 | .map(p -> productIdNameMap.get(p.getKey())).orElse(""); 343 | System.out.println("9. Find the product whose total revenue is highest.: "+productNameString); 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /StreamBeginnerQuestions.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.streams; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class StreamBeginnerQuestions { 7 | public static void main(String[] args) { 8 | 9 | // 1. Filtering Even Numbers 10 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 11 | List evenNumbers = numbers.stream() 12 | .filter(n -> n % 2 == 0) 13 | .collect(Collectors.toList()); 14 | System.out.println("Even Numbers: " + evenNumbers); 15 | 16 | // 2. Convert List of Strings to Uppercase 17 | List words = Arrays.asList("apple", "banana", "cherry"); 18 | List upperCaseWords = words.stream() 19 | .map(String::toUpperCase) 20 | .collect(Collectors.toList()); 21 | System.out.println("Uppercase Words: " + upperCaseWords); 22 | 23 | // 3. Find the First Element that Starts with 'S' 24 | List names = Arrays.asList("John", "Smith", "Sara", "Michael"); 25 | Optional firstSName = names.stream() 26 | .filter(name -> name.startsWith("S")) 27 | .findFirst(); 28 | System.out.println("First name starting with 'S': " + firstSName.orElse("Not found")); 29 | 30 | // 4. Sum of All Elements 31 | Optional sum = numbers.stream() 32 | .reduce((num1, num2) -> num1 + num2); 33 | System.out.println("Sum of Numbers: " + sum.get()); 34 | 35 | // 5. Count Words with Length > 3 36 | List wordList = Arrays.asList("a", "the", "cat", "elephant", "dog"); 37 | long count = wordList.stream() 38 | .filter(word -> word.length() > 3) 39 | .count(); 40 | System.out.println("Count of Words with Length > 3: " + count); 41 | 42 | // 6. Sorting Numbers in Descending Order 43 | List sortedDesc = numbers.stream() 44 | .sorted(Comparator.reverseOrder()) 45 | .collect(Collectors.toList()); 46 | System.out.println("Sorted Numbers (Descending): " + sortedDesc); 47 | 48 | // 7. Remove Duplicates from a List 49 | List duplicateNumbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5, 1); 50 | List uniqueNumbers = duplicateNumbers.stream() 51 | .distinct() 52 | .collect(Collectors.toList()); 53 | System.out.println("Unique Numbers: " + uniqueNumbers); 54 | 55 | // 8. Convert List of Strings to a Single Comma-Separated String 56 | String joinedWords = words.stream() 57 | .collect(Collectors.joining(", ")); 58 | System.out.println("Comma-Separated String: " + joinedWords); 59 | 60 | // 9. Find the Maximum Value 61 | Optional maxNumber = numbers.stream() 62 | .max(Comparator.naturalOrder()); 63 | System.out.println("Maximum Value: " + maxNumber.orElse(-1)); 64 | 65 | // 10. Check if Any String Starts with 'A' 66 | List nameList = Arrays.asList("Bob", "Alice", "Charlie", "Andrew"); 67 | boolean anyStartsWithA = nameList.stream() 68 | .anyMatch(name -> name.startsWith("A")); 69 | System.out.println("Any name starts with 'A': " + anyStartsWithA); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /StreamMediumQuestions.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.streams; 2 | import java.util.*; 3 | import java.util.function.Function; 4 | import java.util.stream.Collectors; 5 | 6 | public class StreamMediumQuestions { 7 | public static void main(String[] args) { 8 | 9 | // 1. Find the Second-Highest Number 10 | // Steps: Remove duplicates -> Sort in descending order -> Skip the highest -> Get the second-highest 11 | List numbers = Arrays.asList(10, 20, 5, 8, 30, 25, 30); 12 | Integer secondHighest = numbers.stream() 13 | .distinct() // Removes duplicate elements 14 | .sorted(Comparator.reverseOrder()) // Sorts elements in descending order 15 | .skip(1) // Skips the first (highest) element 16 | .findFirst() // Retrieves the first element after skipping 17 | .orElse(null); // Returns null if no element found 18 | System.out.println("Second Highest Number: " + secondHighest); 19 | 20 | // 2. Count Occurrences of Each Word 21 | // Steps: Group words -> Count occurrences 22 | List words = Arrays.asList("apple", "banana", "apple", "cherry", "banana", "apple"); 23 | Map wordCount = words.stream() 24 | .collect(Collectors.groupingBy(Function.identity(), // Groups elements by value 25 | Collectors.counting())); // Counts occurrences 26 | System.out.println("Word Count: " + wordCount); 27 | 28 | // 3. Remove Null and Empty Values 29 | // Steps: Remove null values -> Remove empty strings 30 | List values = Arrays.asList("Hello", "", null, "World", "Java", ""); 31 | List filteredValues = values.stream() 32 | .filter(Objects::nonNull) // Filters out null values 33 | .filter(s -> !s.isEmpty()) // Filters out empty strings 34 | .collect(Collectors.toList()); // Collects the remaining values into a list 35 | System.out.println("Filtered Values: " + filteredValues); 36 | 37 | // 4. Find the Longest Word 38 | // Steps: Compare word lengths -> Get the longest 39 | String longestWord = words.stream() 40 | .max(Comparator.comparingInt(String::length)) // Finds the max element based on string length 41 | .orElse(null); // Returns null if no element found 42 | System.out.println("Longest Word: " + longestWord); 43 | 44 | // 5. Convert List of Objects to a Map 45 | // Steps: Convert List to Map 46 | List employees = Arrays.asList(new Employee(1, "John"), new Employee(2, "Jane")); 47 | Map employeeMap = employees.stream() 48 | .collect(Collectors.toMap(Employee::getId, // Key: Employee ID 49 | Employee::getName)); // Value: Employee Name 50 | System.out.println("Employee Map: " + employeeMap); 51 | 52 | // 6. Flatten a List of Lists into a Single List 53 | // Steps: Flatten nested lists into a single list 54 | List> nestedList = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6)); 55 | List flatList = nestedList.stream() 56 | .flatMap(List::stream) // Flattens the nested lists into a single stream 57 | .collect(Collectors.toList()); // Collects the result into a list 58 | System.out.println("Flattened List: " + flatList); 59 | 60 | // 7. Find First Non-Repeating Character in a String 61 | // Steps: Convert to stream -> Count occurrences -> Find the first unique character 62 | String input = "aabbcdeffg"; 63 | Character firstNonRepeating = input.chars() 64 | .mapToObj(c -> (char) c) // Converts int stream to Character stream 65 | .collect(Collectors.groupingBy(Function.identity(), // Groups by character 66 | LinkedHashMap::new, 67 | Collectors.counting())) // Counts occurrences 68 | .entrySet().stream() 69 | .filter(entry -> entry.getValue() == 1) // Filters characters occurring only once 70 | .map(Map.Entry::getKey) // Extracts the character 71 | .findFirst() // Finds the first match 72 | .orElse(null); // Returns null if no match found 73 | System.out.println("First Non-Repeating Character: " + firstNonRepeating); 74 | 75 | // 8. Group Numbers into Even and Odd 76 | // Steps: Partition numbers into even and odd groups 77 | Map> evenOddGrouping = numbers.stream() 78 | .collect(Collectors.partitioningBy(n -> n % 2 == 0)); 79 | // Partitions numbers into true (even) & false (odd) lists 80 | System.out.println("Even & Odd Grouping: " + evenOddGrouping); 81 | 82 | // 9. Sort Strings by Length 83 | // Steps: Sort words based on length 84 | List sortedByLength = words.stream() 85 | .sorted(Comparator.comparingInt(String::length)) // Sorts by string length 86 | .collect(Collectors.toList()); // Collects result into a list 87 | System.out.println("Sorted by Length: " + sortedByLength); 88 | 89 | // 10. Find the Most Repeated Number 90 | // Steps: Count occurrences -> Get the most repeated number 91 | Integer mostRepeated = numbers.stream() 92 | .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 93 | // Groups numbers and counts occurrences 94 | .entrySet().stream() 95 | .max(Map.Entry.comparingByValue()) // Finds entry with the highest count 96 | .map(Map.Entry::getKey) // Extracts the number from the entry 97 | .orElse(null); // Returns null if no match found 98 | System.out.println("Most Repeated Number: " + mostRepeated); 99 | } 100 | } 101 | 102 | class Employee { 103 | private int id; 104 | private String name; 105 | 106 | public Employee(int id, String name) { 107 | this.id = id; 108 | this.name = name; 109 | } 110 | 111 | public int getId() { return id; } 112 | public String getName() { return name; } 113 | } 114 | -------------------------------------------------------------------------------- /StreamScenarioPart1.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.streams; 2 | 3 | import java.util.Comparator; 4 | import java.util.List; 5 | import java.util.Optional; 6 | import java.util.stream.Collectors; 7 | 8 | public class StreamScenarioPart1 { 9 | 10 | public static void main(String a[]) { 11 | List numbers = List.of(1, 2, 7, 3, 4, 5, 2, 3, 6, 7, 8, 8); 12 | 13 | //Remove duplicates 14 | List nonduplicateList = numbers.stream().distinct().collect(Collectors.toList()); 15 | System.out.println(nonduplicateList); 16 | 17 | 18 | 19 | //Find second highest salary 20 | List salaries = List.of(3000,9000, 5000, 7000, 9000, 5000); 21 | Integer secondHighestInteger = salaries.stream() 22 | .distinct() // [3000, 9000, 5000, 7000]. 23 | .sorted(Comparator.reverseOrder()) //[9000, 7000, 5000, 3000]. 24 | .skip(1) // [7000, 5000, 3000]. 25 | .findFirst() 26 | .get(); 27 | System.out.println(secondHighestInteger); 28 | 29 | 30 | 31 | numbers = List.of(2, 4, 6, 7, 10); //List contain one odd number 32 | 33 | //List contains only even numbers 34 | boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0); 35 | 36 | //List does not contain any odd numbers 37 | boolean noOddNumbers = numbers.stream().noneMatch(n -> n % 2 != 0); 38 | 39 | //List contains at least one even number 40 | boolean hasEven = numbers.stream().anyMatch(n -> n % 2 == 0); 41 | 42 | System.out.println("allEven: "+allEven+" noOddNumbers: "+noOddNumbers+" hasEven: "+hasEven); 43 | 44 | 45 | 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /StreamsOnStudentData.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.streams; 2 | 3 | import java.util.*; 4 | import java.util.stream.*; 5 | 6 | class Student { 7 | String firstName, lastName, city, department; 8 | double grade; 9 | int age; 10 | 11 | public Student(String firstName, String lastName, String city, double grade, int age, String department) { 12 | this.firstName = firstName; 13 | this.lastName = lastName; 14 | this.city = city; 15 | this.grade = grade; 16 | this.age = age; 17 | this.department = department; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return firstName + " " + lastName + " (" + city + ", " + grade + ", " + age + ", " + department + ")"; 23 | } 24 | } 25 | 26 | public class AdvancedStreams { 27 | public static void main(String[] args) { 28 | 29 | List students = Arrays.asList( 30 | new Student("John", "Smith", "Miami", 8.38, 19, "Civil"), 31 | new Student("Mike", "Miles", "New York", 8.4, 21, "IT"), 32 | new Student("Michael", "Peterson", "New York", 7.5, 20, "Civil"), 33 | new Student("James", "Robertson", "Miami", 9.1, 20, "IT"), 34 | new Student("John", "Miller", "Miami", 7.83, 20, "Civil") 35 | ); 36 | 37 | // 1. Find students from Miami with a grade greater than 8.0 38 | List miamiHighGrades = students.stream() 39 | .filter(s -> s.city.equals("Miami") && s.grade > 8.0) 40 | .collect(Collectors.toList()); 41 | System.out.println("1. Miami students with grade > 8.0: " + miamiHighGrades); 42 | 43 | // 2. Find the student with the highest grade 44 | Optional topStudent = students.stream() 45 | .max(Comparator.comparingDouble(s -> s.grade)); 46 | System.out.println("2. Student with the highest grade: " + topStudent.orElse(null)); 47 | 48 | // 3. Count the number of students in each department 49 | Map departmentCount = students.stream() 50 | .collect(Collectors.groupingBy(s -> s.department, Collectors.counting())); 51 | System.out.println("3. Number of students per department: " + departmentCount); 52 | 53 | // 4. Find the average grade per department 54 | Map avgGradeByDept = students.stream() 55 | .collect(Collectors.groupingBy(s -> s.department, Collectors.averagingDouble(s -> s.grade))); 56 | System.out.println("4. Average grade per department: " + avgGradeByDept); 57 | 58 | // 5. List students sorted by age and then by grade 59 | List sortedStudents = students.stream() 60 | .sorted(Comparator.comparingInt((Student s) -> s.age).thenComparingDouble(s -> s.grade)) 61 | .collect(Collectors.toList()); 62 | System.out.println("5. Students sorted by age, then grade: " + sortedStudents); 63 | 64 | // 6. Create a comma-separated list of student names 65 | String names = students.stream() 66 | .map(s -> s.firstName + " " + s.lastName) 67 | .collect(Collectors.joining(", ")); 68 | System.out.println("6. Comma-separated student names: " + names); 69 | 70 | // 7. Check if all students are above 18 71 | boolean allAbove18 = students.stream().allMatch(s -> s.age > 18); 72 | System.out.println("7. Are all students above 18? " + allAbove18); 73 | 74 | // 8. Find the department with the most students 75 | String mostPopularDept = students.stream() 76 | .collect(Collectors.groupingBy(s -> s.department, Collectors.counting())).entrySet().stream() 77 | .max(Map.Entry.comparingByValue()) 78 | .map(Map.Entry::getKey) 79 | .orElse("None"); 80 | System.out.println("8. Department with most students: " + mostPopularDept); 81 | 82 | // 9. Divide students into those who have grades above 8.0 and below 83 | Map> gradePartition = students.stream() 84 | .collect(Collectors.partitioningBy(s -> s.grade > 8.0)); 85 | System.out.println("9. Students partitioned by grade: " + gradePartition); 86 | 87 | // 10. Find the student with the longest full name 88 | Optional longestNameStudent = students.stream() 89 | .max(Comparator.comparingInt(s -> (s.firstName + s.lastName).length())); 90 | System.out.println("10. Student with the longest full name: " + longestNameStudent.orElse(null)); 91 | } 92 | } 93 | --------------------------------------------------------------------------------