JAVA Streams - Notes By ShariqSP

Java Streams

Java Streams provide a fluent and functional approach to processing collections of data. They allow developers to perform aggregate operations on elements such as filtering, mapping, sorting, and reduction. Streams are part of the Java Stream API introduced in Java 8, enabling concise and expressive code for data processing tasks. Let's explore Java Streams in detail:

1. Stream Creation:

Streams can be created from various sources such as collections, arrays, or even directly from individual elements. Here's how to create a stream from a collection:


              import java.util.Arrays;
              import java.util.List;
              import java.util.stream.Stream;
              
              public class StreamExample {
                  public static void main(String[] args) {
                      List names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eva");
                      
                      // Creating a stream from a list
                      Stream<String> nameStream = names.stream();
                  }
              }
                

2. Stream Operations:

Streams support various intermediate and terminal operations to perform transformations and produce a result. Here's an example of using filter and map operations:


              import java.util.stream.Collectors;
              
              public class StreamExample {
                  public static void main(String[] args) {
                      List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eva");
                      
                      // Filtering names starting with 'A' and mapping them to uppercase
                      List<String> filteredNames = names.stream()
                                                          .filter(name -> name.startsWith("A"))
                                                          .map(String::toUpperCase)
                                                          .collect(Collectors.toList());
                      
                      System.out.println(filteredNames); // Output: [ALICE]
                  }
              }
                

3. Terminal Operations:

Terminal operations produce a final result or side-effect and close the stream. Common terminal operations include forEach, collect, reduce, and findAny. Here's an example of using collect to gather stream elements into a list:


              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", "Eva");
                      
                      // Collecting stream elements into a list
                      List<String> collectedNames = names.stream()
                                                              .filter(name -> name.length() > 3)
                                                              .collect(Collectors.toList());
                      
                      System.out.println(collectedNames); // Output: [Alice, Charlie, David]
                  }
              }
                

Java Streams provide a powerful and concise way to perform data processing operations on collections in Java. They promote functional programming paradigms and can greatly simplify code for common tasks.

Java Streams

Java Streams provide a convenient way to perform aggregate operations on collections of data. They allow for functional-style operations to be performed on elements such as filtering, mapping, sorting, reducing, and collecting. Let's explore Java Streams with some examples:

Example 1: Filtering

Filter out even numbers from a list of integers:


              List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
              List evenNumbers = numbers.stream()
                                                .filter(n -> n % 2 == 0)
                                                .collect(Collectors.toList());
              System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
                

Example 2: Mapping

Convert a list of strings to uppercase:


              List words = Arrays.asList("apple", "banana", "cherry");
              List upperCaseWords = words.stream()
                                                .map(String::toUpperCase)
                                                .collect(Collectors.toList());
              System.out.println(upperCaseWords); // Output: [APPLE, BANANA, CHERRY]
                

Example 3: Sorting

Sort a list of strings in alphabetical order:


              List fruits = Arrays.asList("banana", "apple", "cherry");
              List sortedFruits = fruits.stream()
                                                .sorted()
                                                .collect(Collectors.toList());
              System.out.println(sortedFruits); // Output: [apple, banana, cherry]
                

Example 4: Reducing

Calculate the sum of all elements in a list of integers:


              List numbers = Arrays.asList(1, 2, 3, 4, 5);
              int sum = numbers.stream()
                              .reduce(0, Integer::sum);
              System.out.println("Sum: " + sum); // Output: Sum: 15
                

Example 5: Collecting

Collect elements of a stream into a map:


              List names = Arrays.asList("John", "Alice", "Bob");
              Map map = names.stream()
                                              .collect(Collectors.toMap(String::length, Function.identity()));
              System.out.println(map); // Output: {4=John, 5=Alice, 3=Bob}
                

Problem Statements to Solve Using Java Streams

  1. Find the sum of all even numbers in a list of integers.
  2. Count the number of occurrences of a specific element in a list of strings.
  3. Determine if all elements in a list of integers are greater than a given threshold.
  4. Find the average length of strings in a list of strings.
  5. Concatenate all strings in a list into a single string.
  6. Find the product of all elements in a list of doubles.
  7. Check if any element in a list of integers is negative.
  8. Merge two lists of strings and remove duplicates.
  9. Sort a list of strings alphabetically and remove duplicates.
  10. Group a list of strings by their lengths.
  11. Find the maximum length of strings in a list of strings.
  12. Calculate the total salary of employees in a list of objects based on their salaries.
  13. Extract unique characters from a list of strings and count their occurrences.
  14. Filter a list of integers to get only prime numbers.
  15. Calculate the factorial of each number in a list of integers.
  16. Convert a list of strings to lowercase and remove whitespace.
  17. Determine if a list of strings contains any palindrome words.
  18. Remove vowels from all strings in a list of strings.
  19. Calculate the square of each number in a list of integers.
  20. Convert a list of objects to a map using a specific attribute as the key.

Solutions for the First 10 Problem Statements Using Java Streams

  1. Find the sum of all even numbers in a list of integers:

    
                  List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
                  int sumOfEvens = numbers.stream()
                                          .filter(n -> n % 2 == 0)
                                          .mapToInt(Integer::intValue)
                                          .sum();
                  System.out.println("Sum of even numbers: " + sumOfEvens);
                        
  2. Count the number of occurrences of a specific element in a list of strings:

    
                  List strings = Arrays.asList("apple", "banana", "apple", "cherry", "apple");
                  long count = strings.stream()
                                     .filter(s -> s.equals("apple"))
                                     .count();
                  System.out.println("Occurrences of 'apple': " + count);
                        
  3. Determine if all elements in a list of integers are greater than a given threshold:

    
                  List numbers = Arrays.asList(10, 20, 30, 40, 50);
                  int threshold = 25;
                  boolean allGreaterThanThreshold = numbers.stream()
                                                           .allMatch(n -> n > threshold);
                  System.out.println("All numbers greater than " + threshold + ": " + allGreaterThanThreshold);
                        
  4. Find the average length of strings in a list of strings:

    
                  List strings = Arrays.asList("apple", "banana", "cherry");
                  double averageLength = strings.stream()
                                              .mapToInt(String::length)
                                              .average()
                                              .orElse(0);
                  System.out.println("Average length of strings: " + averageLength);
                        
  5. Concatenate all strings in a list into a single string:

    
                  List strings = Arrays.asList("Hello", "World", "!");
                  String concatenated = strings.stream()
                                               .reduce("", (s1, s2) -> s1 + s2);
                  System.out.println("Concatenated string: " + concatenated);
                        
  6. Find the product of all elements in a list of doubles:

    
                  List numbers = Arrays.asList(1.5, 2.5, 3.5, 4.5);
                  double product = numbers.stream()
                                         .reduce(1.0, (d1, d2) -> d1 * d2);
                  System.out.println("Product of elements: " + product);
                        
  7. Check if any element in a list of integers is negative:

    
                  List numbers = Arrays.asList(1, 2, -3, 4, 5);
                  boolean anyNegative = numbers.stream()
                                               .anyMatch(n -> n < 0);
                  System.out.println("Any negative number: " + anyNegative);
                        
  8. Merge two lists of strings and remove duplicates:

    
                  List list1 = Arrays.asList("apple", "banana");
                  List list2 = Arrays.asList("banana", "cherry");
                  List mergedAndDistinct = Stream.concat(list1.stream(), list2.stream())
                                                        .distinct()
                                                        .collect(Collectors.toList());
                  System.out.println("Merged and distinct list: " + mergedAndDistinct);
                        
  9. Sort a list of strings alphabetically and remove duplicates:

    
                  List strings = Arrays.asList("banana", "apple", "cherry", "banana");
                  List sortedAndDistinct = strings.stream()
                                                         .sorted()
                                                         .distinct()
                                                         .collect(Collectors.toList());
                  System.out.println("Sorted and distinct list: " + sortedAndDistinct);
                        
  10. Group a list of strings by their lengths:

    
                  List strings = Arrays.asList("apple", "banana", "cherry", "grape");
                  Map> groupedByLength = strings.stream()
                                                                    .collect(Collectors.groupingBy(String::length));
                  System.out.println("Grouped by length: " + groupedByLength);